threads
listlengths
1
2.99k
[ { "msg_contents": "Hello!\n\nI`ve noticed, that when running switchover replica to master and back to \nreplica, new history file is streamed to replica, but not archived,\nwhich is not great, because it breaks PITR if archiving is running on \nreplica. The fix looks trivial.\nBash script to reproduce the problem and patch are attached.\n\n-- \nGrigory Smolkin\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Thu, 27 Aug 2020 16:02:44 +0300", "msg_from": "Grigory Smolkin <g.smolkin@postgrespro.ru>", "msg_from_op": true, "msg_subject": "history file on replica and double switchover" }, { "msg_contents": "On 27.08.2020 16:02, Grigory Smolkin wrote:\n> Hello!\n>\n> I`ve noticed, that when running switchover replica to master and back \n> to replica, new history file is streamed to replica, but not archived,\n> which is not great, because it breaks PITR if archiving is running on \n> replica. The fix looks trivial.\n> Bash script to reproduce the problem and patch are attached.\n>\nThanks for the report. I agree that it looks like a bug.\n\nFor some reason, patch failed to apply on current master, even though I \ndon't see any difference in the code.\nI'll attach this thread to the next commitfest, so it doesn't get lost.\n\n-- \nAnastasia Lubennikova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Fri, 4 Sep 2020 02:29:36 +0300", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: history file on replica and double switchover" }, { "msg_contents": "\n\nOn 2020/09/04 8:29, Anastasia Lubennikova wrote:\n> On 27.08.2020 16:02, Grigory Smolkin wrote:\n>> Hello!\n>>\n>> I`ve noticed, that when running switchover replica to master and back to replica, new history file is streamed to replica, but not archived,\n>> which is not great, because it breaks PITR if archiving is running on replica. The fix looks trivial.\n>> Bash script to reproduce the problem and patch are attached.\n>>\n> Thanks for the report. I agree that it looks like a bug.\n\n+1\n\n+\t\t\t/* Mark history file as ready for archiving */\n+\t\t\tif (XLogArchiveMode != ARCHIVE_MODE_OFF)\n+\t\t\t\tXLogArchiveNotify(fname);\n\nI agree that history file should be archived in the standby when\narchive_mode=always. But why do we need to do when archive_mode=on?\nI'm just concerned about the case where the primary and standby\nhave the shared archive area, and archive_mode is on.\n\n\n> For some reason, patch failed to apply on current master, even though I don't see any difference in the code.\n> I'll attach this thread to the next commitfest, so it doesn't get lost.\n\nThanks!\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Fri, 4 Sep 2020 13:53:24 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: history file on replica and double switchover" }, { "msg_contents": "On 2020/09/04 13:53, Fujii Masao wrote:\n> \n> \n> On 2020/09/04 8:29, Anastasia Lubennikova wrote:\n>> On 27.08.2020 16:02, Grigory Smolkin wrote:\n>>> Hello!\n>>>\n>>> I`ve noticed, that when running switchover replica to master and back to replica, new history file is streamed to replica, but not archived,\n>>> which is not great, because it breaks PITR if archiving is running on replica. The fix looks trivial.\n>>> Bash script to reproduce the problem and patch are attached.\n>>>\n>> Thanks for the report. I agree that it looks like a bug.\n> \n> +1\n> \n> +            /* Mark history file as ready for archiving */\n> +            if (XLogArchiveMode != ARCHIVE_MODE_OFF)\n> +                XLogArchiveNotify(fname);\n> \n> I agree that history file should be archived in the standby when\n> archive_mode=always. But why do we need to do when archive_mode=on?\n> I'm just concerned about the case where the primary and standby\n> have the shared archive area, and archive_mode is on.\n\nSo I updated the patch so that walreceiver marks the streamed history file\nas ready for archiving only when archive_mode=always. Patch attached.\nThought?\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION", "msg_date": "Fri, 18 Sep 2020 02:18:45 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: history file on replica and double switchover" }, { "msg_contents": "Hi,\n\nMy understanding is that the \"archiver\" won't even start if \n\"archive_mode = on\" has been set on a \"replica\". Therefore, either \n(XLogArchiveMode == ARCHIVE_MODE_ALWAYS) or (XLogArchiveMode != \nARCHIVE_MODE_OFF) will produce the same result.\n\nPlease see how the \"archiver\" is started in \nsrc/backend/postmaster/postmaster.c\n\n5227                 /*\n5228                  * Start the archiver if we're responsible for \n(re-)archiving received\n5229                  * files.\n5230                  */\n5231                 Assert(PgArchPID == 0);\n5232                 if (XLogArchivingAlways())\n5233                         PgArchPID = pgarch_start();\n\nI did run the nice script \"double_switchover.sh\" using either \"always\" \nor \"on\" on patch v1 and v2. They all generate the same results below. In \nother words, whether history file (00000003.history) is archived or not \ndepends on \"archive_mode\" settings.\n\necho \"archive_mode = always\" >> ${PGDATA_NODE2}/postgresql.auto.conf\n\n$ ls -l archive\n-rw------- 1 david david 16777216 Sep 24 14:40 000000010000000000000002\n... ...\n-rw------- 1 david david 16777216 Sep 24 14:40 00000002000000000000000A\n-rw------- 1 david david       41 Sep 24 14:40 00000002.history\n-rw------- 1 david david       83 Sep 24 14:40 00000003.history\n\necho \"archive_mode = on\" >> ${PGDATA_NODE2}/postgresql.auto.conf\n\n$ ls -l archive\n-rw------- 1 david david 16777216 Sep 24 14:47 000000010000000000000002\n... ...\n-rw------- 1 david david 16777216 Sep 24 14:47 00000002000000000000000A\n-rw------- 1 david david       41 Sep 24 14:47 00000002.history\n\n\nPersonally, I prefer patch v2 since it allies to the statement here, \nhttps://www.postgresql.org/docs/13/warm-standby.html#CONTINUOUS-ARCHIVING-IN-STANDBY\n\n\"If archive_mode is set to on, the archiver is not enabled during \nrecovery or standby mode. If the standby server is promoted, it will \nstart archiving after the promotion, but will not archive any WAL it did \nnot generate itself.\"\n\nBy the way, I think the last part of the sentence should be changed to \nsomething like below:\n\n\"but will not archive any WAL, which was not generated by itself.\"\n\n\nBest regards,\n\nDavid\n\nOn 2020-09-17 10:18 a.m., Fujii Masao wrote:\n>\n>\n> On 2020/09/04 13:53, Fujii Masao wrote:\n>>\n>>\n>> On 2020/09/04 8:29, Anastasia Lubennikova wrote:\n>>> On 27.08.2020 16:02, Grigory Smolkin wrote:\n>>>> Hello!\n>>>>\n>>>> I`ve noticed, that when running switchover replica to master and \n>>>> back to replica, new history file is streamed to replica, but not \n>>>> archived,\n>>>> which is not great, because it breaks PITR if archiving is running \n>>>> on replica. The fix looks trivial.\n>>>> Bash script to reproduce the problem and patch are attached.\n>>>>\n>>> Thanks for the report. I agree that it looks like a bug.\n>>\n>> +1\n>>\n>> +            /* Mark history file as ready for archiving */\n>> +            if (XLogArchiveMode != ARCHIVE_MODE_OFF)\n>> +                XLogArchiveNotify(fname);\n>>\n>> I agree that history file should be archived in the standby when\n>> archive_mode=always. But why do we need to do when archive_mode=on?\n>> I'm just concerned about the case where the primary and standby\n>> have the shared archive area, and archive_mode is on.\n>\n> So I updated the patch so that walreceiver marks the streamed history \n> file\n> as ready for archiving only when archive_mode=always. Patch attached.\n> Thought?\n>\n> Regards,\n>\n-- \nDavid\n\nSoftware Engineer\nHighgo Software Inc. (Canada)\nwww.highgo.ca\n\n\n\n", "msg_date": "Thu, 24 Sep 2020 16:15:17 -0700", "msg_from": "David Zhang <david.zhang@highgo.ca>", "msg_from_op": false, "msg_subject": "Re: history file on replica and double switchover" }, { "msg_contents": "\n\nOn 2020/09/25 8:15, David Zhang wrote:\n> Hi,\n> \n> My understanding is that the \"archiver\" won't even start if \"archive_mode = on\" has been set on a \"replica\". Therefore, either (XLogArchiveMode == ARCHIVE_MODE_ALWAYS) or (XLogArchiveMode != ARCHIVE_MODE_OFF) will produce the same result.\n\nYes, the archiver isn't invoked in the standby when archive_mode=on.\nBut, with the original patch, walreceiver creates .ready archive status file\neven when archive_mode=on and no archiver is running. This causes\nthe history file to be archived after the standby is promoted and\nthe archiver is invoked.\n\nWith my patch, walreceiver creates .ready archive status for the history file\nonly when archive_mode=always, like it does for the streamed WAL files.\nThis is the difference between those two patches. To prevent the streamed\ntimeline history file from being archived, IMO we should use the condition\narchive_mode==always in the walreceiver.\n\n\n> \n> Please see how the \"archiver\" is started in src/backend/postmaster/postmaster.c\n> \n> 5227                 /*\n> 5228                  * Start the archiver if we're responsible for (re-)archiving received\n> 5229                  * files.\n> 5230                  */\n> 5231                 Assert(PgArchPID == 0);\n> 5232                 if (XLogArchivingAlways())\n> 5233                         PgArchPID = pgarch_start();\n> \n> I did run the nice script \"double_switchover.sh\" using either \"always\" or \"on\" on patch v1 and v2. They all generate the same results below. In other words, whether history file (00000003.history) is archived or not depends on \"archive_mode\" settings.\n> \n> echo \"archive_mode = always\" >> ${PGDATA_NODE2}/postgresql.auto.conf\n> \n> $ ls -l archive\n> -rw------- 1 david david 16777216 Sep 24 14:40 000000010000000000000002\n> ... ...\n> -rw------- 1 david david 16777216 Sep 24 14:40 00000002000000000000000A\n> -rw------- 1 david david       41 Sep 24 14:40 00000002.history\n> -rw------- 1 david david       83 Sep 24 14:40 00000003.history\n> \n> echo \"archive_mode = on\" >> ${PGDATA_NODE2}/postgresql.auto.conf\n> \n> $ ls -l archive\n> -rw------- 1 david david 16777216 Sep 24 14:47 000000010000000000000002\n> ... ...\n> -rw------- 1 david david 16777216 Sep 24 14:47 00000002000000000000000A\n> -rw------- 1 david david       41 Sep 24 14:47 00000002.history\n> \n> \n> Personally, I prefer patch v2 since it allies to the statement here, https://www.postgresql.org/docs/13/warm-standby.html#CONTINUOUS-ARCHIVING-IN-STANDBY\n> \n> \"If archive_mode is set to on, the archiver is not enabled during recovery or standby mode. If the standby server is promoted, it will start archiving after the promotion, but will not archive any WAL it did not generate itself.\"\n> \n> By the way, I think the last part of the sentence should be changed to something like below:\n> \n> \"but will not archive any WAL, which was not generated by itself.\"\n\nI'm not sure if this change is an improvement or not. But if we apply\nthe patch I proposed, maybe we should mention also history file here.\nFor example, \"but will not archive any WAL or timeline history files\nthat it did not generate itself\".\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Fri, 25 Sep 2020 09:00:11 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: history file on replica and double switchover" }, { "msg_contents": "On 2020-09-24 5:00 p.m., Fujii Masao wrote:\n>\n>\n> On 2020/09/25 8:15, David Zhang wrote:\n>> Hi,\n>>\n>> My understanding is that the \"archiver\" won't even start if \n>> \"archive_mode = on\" has been set on a \"replica\". Therefore, either \n>> (XLogArchiveMode == ARCHIVE_MODE_ALWAYS) or (XLogArchiveMode != \n>> ARCHIVE_MODE_OFF) will produce the same result.\n>\n> Yes, the archiver isn't invoked in the standby when archive_mode=on.\n> But, with the original patch, walreceiver creates .ready archive \n> status file\n> even when archive_mode=on and no archiver is running. This causes\n> the history file to be archived after the standby is promoted and\n> the archiver is invoked.\n>\n> With my patch, walreceiver creates .ready archive status for the \n> history file\n> only when archive_mode=always, like it does for the streamed WAL files.\n> This is the difference between those two patches. To prevent the streamed\n> timeline history file from being archived, IMO we should use the \n> condition\n> archive_mode==always in the walreceiver.\n+1\n>\n>\n>>\n>> Please see how the \"archiver\" is started in \n>> src/backend/postmaster/postmaster.c\n>>\n>> 5227                 /*\n>> 5228                  * Start the archiver if we're responsible for \n>> (re-)archiving received\n>> 5229                  * files.\n>> 5230                  */\n>> 5231                 Assert(PgArchPID == 0);\n>> 5232                 if (XLogArchivingAlways())\n>> 5233                         PgArchPID = pgarch_start();\n>>\n>> I did run the nice script \"double_switchover.sh\" using either \n>> \"always\" or \"on\" on patch v1 and v2. They all generate the same \n>> results below. In other words, whether history file \n>> (00000003.history) is archived or not depends on \"archive_mode\" \n>> settings.\n>>\n>> echo \"archive_mode = always\" >> ${PGDATA_NODE2}/postgresql.auto.conf\n>>\n>> $ ls -l archive\n>> -rw------- 1 david david 16777216 Sep 24 14:40 000000010000000000000002\n>> ... ...\n>> -rw------- 1 david david 16777216 Sep 24 14:40 00000002000000000000000A\n>> -rw------- 1 david david       41 Sep 24 14:40 00000002.history\n>> -rw------- 1 david david       83 Sep 24 14:40 00000003.history\n>>\n>> echo \"archive_mode = on\" >> ${PGDATA_NODE2}/postgresql.auto.conf\n>>\n>> $ ls -l archive\n>> -rw------- 1 david david 16777216 Sep 24 14:47 000000010000000000000002\n>> ... ...\n>> -rw------- 1 david david 16777216 Sep 24 14:47 00000002000000000000000A\n>> -rw------- 1 david david       41 Sep 24 14:47 00000002.history\n>>\n>>\n>> Personally, I prefer patch v2 since it allies to the statement here, \n>> https://www.postgresql.org/docs/13/warm-standby.html#CONTINUOUS-ARCHIVING-IN-STANDBY\n>>\n>> \"If archive_mode is set to on, the archiver is not enabled during \n>> recovery or standby mode. If the standby server is promoted, it will \n>> start archiving after the promotion, but will not archive any WAL it \n>> did not generate itself.\"\n>>\n>> By the way, I think the last part of the sentence should be changed \n>> to something like below:\n>>\n>> \"but will not archive any WAL, which was not generated by itself.\"\n>\n> I'm not sure if this change is an improvement or not. But if we apply\n> the patch I proposed, maybe we should mention also history file here.\n> For example, \"but will not archive any WAL or timeline history files\n> that it did not generate itself\".\nmake sense for me\n>\n> Regards,\n>\n-- \nDavid\n\nSoftware Engineer\nHighgo Software Inc. (Canada)\nwww.highgo.ca\n\n\n\n", "msg_date": "Thu, 24 Sep 2020 21:00:19 -0700", "msg_from": "David Zhang <david.zhang@highgo.ca>", "msg_from_op": false, "msg_subject": "Re: history file on replica and double switchover" }, { "msg_contents": "On 2020/09/25 13:00, David Zhang wrote:\n> On 2020-09-24 5:00 p.m., Fujii Masao wrote:\n>>\n>>\n>> On 2020/09/25 8:15, David Zhang wrote:\n>>> Hi,\n>>>\n>>> My understanding is that the \"archiver\" won't even start if \"archive_mode = on\" has been set on a \"replica\". Therefore, either (XLogArchiveMode == ARCHIVE_MODE_ALWAYS) or (XLogArchiveMode != ARCHIVE_MODE_OFF) will produce the same result.\n>>\n>> Yes, the archiver isn't invoked in the standby when archive_mode=on.\n>> But, with the original patch, walreceiver creates .ready archive status file\n>> even when archive_mode=on and no archiver is running. This causes\n>> the history file to be archived after the standby is promoted and\n>> the archiver is invoked.\n>>\n>> With my patch, walreceiver creates .ready archive status for the history file\n>> only when archive_mode=always, like it does for the streamed WAL files.\n>> This is the difference between those two patches. To prevent the streamed\n>> timeline history file from being archived, IMO we should use the condition\n>> archive_mode==always in the walreceiver.\n> +1\n>>\n>>\n>>>\n>>> Please see how the \"archiver\" is started in src/backend/postmaster/postmaster.c\n>>>\n>>> 5227                 /*\n>>> 5228                  * Start the archiver if we're responsible for (re-)archiving received\n>>> 5229                  * files.\n>>> 5230                  */\n>>> 5231                 Assert(PgArchPID == 0);\n>>> 5232                 if (XLogArchivingAlways())\n>>> 5233                         PgArchPID = pgarch_start();\n>>>\n>>> I did run the nice script \"double_switchover.sh\" using either \"always\" or \"on\" on patch v1 and v2. They all generate the same results below. In other words, whether history file (00000003.history) is archived or not depends on \"archive_mode\" settings.\n>>>\n>>> echo \"archive_mode = always\" >> ${PGDATA_NODE2}/postgresql.auto.conf\n>>>\n>>> $ ls -l archive\n>>> -rw------- 1 david david 16777216 Sep 24 14:40 000000010000000000000002\n>>> ... ...\n>>> -rw------- 1 david david 16777216 Sep 24 14:40 00000002000000000000000A\n>>> -rw------- 1 david david       41 Sep 24 14:40 00000002.history\n>>> -rw------- 1 david david       83 Sep 24 14:40 00000003.history\n>>>\n>>> echo \"archive_mode = on\" >> ${PGDATA_NODE2}/postgresql.auto.conf\n>>>\n>>> $ ls -l archive\n>>> -rw------- 1 david david 16777216 Sep 24 14:47 000000010000000000000002\n>>> ... ...\n>>> -rw------- 1 david david 16777216 Sep 24 14:47 00000002000000000000000A\n>>> -rw------- 1 david david       41 Sep 24 14:47 00000002.history\n>>>\n>>>\n>>> Personally, I prefer patch v2 since it allies to the statement here, https://www.postgresql.org/docs/13/warm-standby.html#CONTINUOUS-ARCHIVING-IN-STANDBY\n>>>\n>>> \"If archive_mode is set to on, the archiver is not enabled during recovery or standby mode. If the standby server is promoted, it will start archiving after the promotion, but will not archive any WAL it did not generate itself.\"\n>>>\n>>> By the way, I think the last part of the sentence should be changed to something like below:\n>>>\n>>> \"but will not archive any WAL, which was not generated by itself.\"\n>>\n>> I'm not sure if this change is an improvement or not. But if we apply\n>> the patch I proposed, maybe we should mention also history file here.\n>> For example, \"but will not archive any WAL or timeline history files\n>> that it did not generate itself\".\n> make sense for me\n\nSo I included this change in the patch. Patch attached.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION", "msg_date": "Fri, 25 Sep 2020 16:07:17 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: history file on replica and double switchover" }, { "msg_contents": "Fujii Masao, David Zhang, Anastasia Lubennikova, many thanks to you for \nefforts with this patch!\nCan I mark it as ready for committer?\n\nOn 9/25/20 10:07 AM, Fujii Masao wrote:\n>\n>\n> On 2020/09/25 13:00, David Zhang wrote:\n>> On 2020-09-24 5:00 p.m., Fujii Masao wrote:\n>>>\n>>>\n>>> On 2020/09/25 8:15, David Zhang wrote:\n>>>> Hi,\n>>>>\n>>>> My understanding is that the \"archiver\" won't even start if \n>>>> \"archive_mode = on\" has been set on a \"replica\". Therefore, either \n>>>> (XLogArchiveMode == ARCHIVE_MODE_ALWAYS) or (XLogArchiveMode != \n>>>> ARCHIVE_MODE_OFF) will produce the same result.\n>>>\n>>> Yes, the archiver isn't invoked in the standby when archive_mode=on.\n>>> But, with the original patch, walreceiver creates .ready archive \n>>> status file\n>>> even when archive_mode=on and no archiver is running. This causes\n>>> the history file to be archived after the standby is promoted and\n>>> the archiver is invoked.\n>>>\n>>> With my patch, walreceiver creates .ready archive status for the \n>>> history file\n>>> only when archive_mode=always, like it does for the streamed WAL files.\n>>> This is the difference between those two patches. To prevent the \n>>> streamed\n>>> timeline history file from being archived, IMO we should use the \n>>> condition\n>>> archive_mode==always in the walreceiver.\n>> +1\n>>>\n>>>\n>>>>\n>>>> Please see how the \"archiver\" is started in \n>>>> src/backend/postmaster/postmaster.c\n>>>>\n>>>> 5227                 /*\n>>>> 5228                  * Start the archiver if we're responsible for \n>>>> (re-)archiving received\n>>>> 5229                  * files.\n>>>> 5230                  */\n>>>> 5231                 Assert(PgArchPID == 0);\n>>>> 5232                 if (XLogArchivingAlways())\n>>>> 5233                         PgArchPID = pgarch_start();\n>>>>\n>>>> I did run the nice script \"double_switchover.sh\" using either \n>>>> \"always\" or \"on\" on patch v1 and v2. They all generate the same \n>>>> results below. In other words, whether history file \n>>>> (00000003.history) is archived or not depends on \"archive_mode\" \n>>>> settings.\n>>>>\n>>>> echo \"archive_mode = always\" >> ${PGDATA_NODE2}/postgresql.auto.conf\n>>>>\n>>>> $ ls -l archive\n>>>> -rw------- 1 david david 16777216 Sep 24 14:40 \n>>>> 000000010000000000000002\n>>>> ... ...\n>>>> -rw------- 1 david david 16777216 Sep 24 14:40 \n>>>> 00000002000000000000000A\n>>>> -rw------- 1 david david       41 Sep 24 14:40 00000002.history\n>>>> -rw------- 1 david david       83 Sep 24 14:40 00000003.history\n>>>>\n>>>> echo \"archive_mode = on\" >> ${PGDATA_NODE2}/postgresql.auto.conf\n>>>>\n>>>> $ ls -l archive\n>>>> -rw------- 1 david david 16777216 Sep 24 14:47 \n>>>> 000000010000000000000002\n>>>> ... ...\n>>>> -rw------- 1 david david 16777216 Sep 24 14:47 \n>>>> 00000002000000000000000A\n>>>> -rw------- 1 david david       41 Sep 24 14:47 00000002.history\n>>>>\n>>>>\n>>>> Personally, I prefer patch v2 since it allies to the statement \n>>>> here, \n>>>> https://www.postgresql.org/docs/13/warm-standby.html#CONTINUOUS-ARCHIVING-IN-STANDBY\n>>>>\n>>>> \"If archive_mode is set to on, the archiver is not enabled during \n>>>> recovery or standby mode. If the standby server is promoted, it \n>>>> will start archiving after the promotion, but will not archive any \n>>>> WAL it did not generate itself.\"\n>>>>\n>>>> By the way, I think the last part of the sentence should be changed \n>>>> to something like below:\n>>>>\n>>>> \"but will not archive any WAL, which was not generated by itself.\"\n>>>\n>>> I'm not sure if this change is an improvement or not. But if we apply\n>>> the patch I proposed, maybe we should mention also history file here.\n>>> For example, \"but will not archive any WAL or timeline history files\n>>> that it did not generate itself\".\n>> make sense for me\n>\n> So I included this change in the patch. Patch attached.\n>\n> Regards,\n>\n-- \nGrigory Smolkin\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Fri, 25 Sep 2020 20:58:07 +0300", "msg_from": "Grigory Smolkin <g.smolkin@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: history file on replica and double switchover" }, { "msg_contents": "On 2020/09/26 2:58, Grigory Smolkin wrote:\n> Fujii Masao, David Zhang, Anastasia Lubennikova, many thanks to you for efforts with this patch!\n> Can I mark it as ready for committer?\n\nOk, but I attached the updated version of the patch. It's helpful if you review that.\n\nIn the latest patch, I changed walreceiver so that it creates .done file for the streamed timeline history file when archive_mode is NOT \"always\".\n\nWalreceiver does the same thing for the streamed WAL files to prevent them from being archived later. Without this, the streamed WAL files can exist in pg_wal without any archive status files, and then they will be archived later accidentally because of lack of archive status.\n\nOTOH, timeline history files will not be archived later even without archive status files. So there is no strong reason to make walreceiver create .doen file for the timeline history files. But at least for me it's strange to keep the file in pg_wal without archive status. So for now I'm just inclined to create .done files.... Thought?\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION", "msg_date": "Sat, 26 Sep 2020 04:05:00 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: history file on replica and double switchover" }, { "msg_contents": "The following review has been posted through the commitfest application:\nmake installcheck-world: tested, failed\nImplements feature: tested, passed\nSpec compliant: tested, passed\nDocumentation: tested, passed\n\n\"make installcheck-world\" test was performed on branch \"REL_13_STABLE\" with tag \"REL_13_0\". The regression failed was not caused by the \"history file\" patch, since it has the same error on my environment even without any patch. So the failure is not related, in other words, the patch \"history_replica_v4.patch\" is good for me. \r\n\r\nBelow is the failed message when tested with and without \"history_replica_v4.patch\".\r\nt/004_timeline_switch.pl ............. ok \r\nt/005_replay_delay.pl ................ ok \r\nt/006_logical_decoding.pl ............ # Looks like your test exited with 29 before it could output anything.\r\nt/006_logical_decoding.pl ............ Dubious, test returned 29 (wstat 7424, 0x1d00)\r\nFailed 14/14 subtests \r\nt/007_sync_rep.pl .................... ok \r\nt/008_fsm_truncation.pl .............. ok \r\nt/009_twophase.pl .................... ok \r\nt/010_logical_decoding_timelines.pl .. # Looks like your test exited with 29 before it could output anything.\r\nt/010_logical_decoding_timelines.pl .. Dubious, test returned 29 (wstat 7424, 0x1d00)\r\nFailed 13/13 subtests \r\nt/011_crash_recovery.pl .............. ok \r\nt/012_subtransactions.pl ............. ok \r\nt/013_crash_restart.pl ............... ok \r\nt/014_unlogged_reinit.pl ............. ok \r\nt/015_promotion_pages.pl ............. ok \r\nt/016_min_consistency.pl ............. ok \r\nt/017_shm.pl ......................... ok \r\nt/018_wal_optimize.pl ................ ok \r\nt/019_replslot_limit.pl .............. ok \r\nt/020_archive_status.pl .............. ok \r\n\r\nTest Summary Report\r\n-------------------\r\nt/006_logical_decoding.pl (Wstat: 7424 Tests: 0 Failed: 0)\r\n Non-zero exit status: 29\r\n Parse errors: Bad plan. You planned 14 tests but ran 0.\r\nt/010_logical_decoding_timelines.pl (Wstat: 7424 Tests: 0 Failed: 0)\r\n Non-zero exit status: 29\r\n Parse errors: Bad plan. You planned 13 tests but ran 0.\r\nFiles=20, Tests=202, 103 wallclock secs ( 0.18 usr 0.04 sys + 21.20 cusr 23.52 csys = 44.94 CPU)\r\nResult: FAIL\r\nmake[2]: *** [installcheck] Error 1\r\nmake[2]: Leaving directory `/home/david/git/postgres/src/test/recovery'\r\nmake[1]: *** [installcheck-recovery-recurse] Error 2\r\nmake[1]: Leaving directory `/home/david/git/postgres/src/test'\r\nmake: *** [installcheck-world-src/test-recurse] Error 2", "msg_date": "Fri, 25 Sep 2020 20:34:32 +0000", "msg_from": "David Zhang <david.zhang@highgo.ca>", "msg_from_op": false, "msg_subject": "Re: history file on replica and double switchover" }, { "msg_contents": "\n\nOn 2020/09/26 5:34, David Zhang wrote:\n> The following review has been posted through the commitfest application:\n> make installcheck-world: tested, failed\n> Implements feature: tested, passed\n> Spec compliant: tested, passed\n> Documentation: tested, passed\n> \n> \"make installcheck-world\" test was performed on branch \"REL_13_STABLE\" with tag \"REL_13_0\". The regression failed was not caused by the \"history file\" patch, since it has the same error on my environment even without any patch. So the failure is not related, in other words, the patch \"history_replica_v4.patch\" is good for me.\n\nThanks for the check! I pushed the patch. Thanks!\n\n\n> Below is the failed message when tested with and without \"history_replica_v4.patch\".\n\nBTW, I could not reproduce this issue in my env.\nI'm not sure why this failure happened in your env....\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Tue, 29 Sep 2020 16:32:44 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: history file on replica and double switchover" } ]
[ { "msg_contents": ">checking for libxml/parser.h... no\n>configure: error: header file <libxml/parser.h> is required for XML support\n\nsudo yum install libxml2-devel\n\nYou need to install the development package before ./configure.\n\nregards,\nRanier Vilela\n\n>checking for libxml/parser.h... no>configure: error: header file <libxml/parser.h> is required for XML support\nsudo yum install libxml2-develYou need to install the development package before ./configure.regards,Ranier Vilela", "msg_date": "Thu, 27 Aug 2020 10:16:22 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "re: Please help for error ( file <libxml/parser.h> is required for\n XML support )" }, { "msg_contents": "Package libxml2-devel-2.9.1-6.el7.4.ppc64le is already installed.\r\n\r\nThanks and Regards,\r\nSACHIN KHANNA\r\n212 BASIS DBA TEAM OFFSHORE\r\nOffice : 204058624\r\nCell : 9049522511\r\n\r\n\r\nFrom: Ranier Vilela <ranier.vf@gmail.com>\r\nSent: Thursday, August 27, 2020 6:46 PM\r\nTo: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>\r\nCc: Sachin Khanna <Sachin_Khanna@infosys.com>\r\nSubject: re: Please help for error ( file <libxml/parser.h> is required for XML support )\r\n\r\n\r\n[**EXTERNAL EMAIL**]\r\n>checking for libxml/parser.h... no\r\n>configure: error: header file <libxml/parser.h> is required for XML support\r\n\r\nsudo yum install libxml2-devel\r\n\r\nYou need to install the development package before ./configure.\r\n\r\nregards,\r\nRanier Vilela\r\n\r\n\n\n\n\n\n\n\n\n\nPackage libxml2-devel-2.9.1-6.el7.4.ppc64le is already installed.\n \n\nThanks and Regards,\r\nSACHIN KHANNA\r\n212 BASIS DBA TEAM OFFSHORE\nOffice : 204058624\r\nCell : 9049522511\n\n\n\n \n\n\nFrom: Ranier Vilela <ranier.vf@gmail.com> \nSent: Thursday, August 27, 2020 6:46 PM\nTo: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>\nCc: Sachin Khanna <Sachin_Khanna@infosys.com>\nSubject: re: Please help for error ( file <libxml/parser.h> is required for XML support )\n\n\n \n[**EXTERNAL EMAIL**]\n\n\n\n>checking for libxml/parser.h... no\r\n>configure: error: header file <libxml/parser.h> is required for XML support\n\n \n\nsudo yum install libxml2-devel\n\n\n \n\n\nYou need to install the development package before ./configure.\n\n\n \n\n\nregards,\n\n\nRanier Vilela", "msg_date": "Fri, 28 Aug 2020 06:44:22 +0000", "msg_from": "Sachin Khanna <Sachin_Khanna@infosys.com>", "msg_from_op": false, "msg_subject": "RE: Please help for error ( file <libxml/parser.h> is required for\n XML support )" }, { "msg_contents": "Now I can see the that libraries are identified in config.log . I also found some error in configuration file as well. Highlight below.\r\nPlease find the attached config.log file for reference.\r\nPlease help and let me know if I there is any issue in configuration script and I need to change it ?\r\n\r\nI am using PostgreSQL version postgresql-12.3.tar.gz\r\n\r\nconfigure:8291: checking for XML2_CONFIG\r\nconfigure:8293: result: /usr/lib64/libxml2.so\r\nconfigure:8416: checking for grep that handles long lines and -e\r\nconfigure:8474: result: /bin/grep\r\nconfigure:8479: checking for egrep\r\nconfigure:8541: result: /bin/grep -E\r\nconfigure:8588: checking for ld used by GCC\r\nconfigure:8651: result: /bin/ld\r\nconfigure:8658: checking if the linker (/bin/ld) is GNU ld\r\nGNU ld version 2.27-44.base.el7\r\n\r\nat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -D_GNU_SOURCE conftest.c >&5\r\nconftest.c: In function 'main':\r\nconftest.c:76:20: error: expected expression before ')' token\r\nif (sizeof ((_Bool)))\r\n ^\r\nconfigure:12910: $? = 1\r\nconfigure: failed program was:\r\n| /* confdefs.h */\r\n\r\nat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -D_GNU_SOURCE conftest.c >&5\r\nconftest.c:75:20: fatal error: atomic.h: No such file or directory\r\n#include <atomic.h>\r\n ^\r\ncompilation terminated.\r\n\r\n\r\n| #include <libxml/parser.h>\r\nconfigure:13266: result: no\r\nconfigure:13266: checking libxml/parser.h presence\r\nconfigure:13266: gcc -std=gnu99 -E -D_GNU_SOURCE conftest.c\r\nconftest.c:63:27: fatal error: libxml/parser.h: No such file or directory\r\n#include <libxml/parser.h>\r\n ^\r\ncompilation terminated.\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nThanks and Regards,\r\nSACHIN KHANNA\r\n212 BASIS DBA TEAM OFFSHORE\r\nOffice : 204058624\r\nCell : 9049522511\r\n\r\n\r\nFrom: Sachin Khanna\r\nSent: Friday, August 28, 2020 12:14 PM\r\nTo: 'Ranier Vilela' <ranier.vf@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>\r\nSubject: RE: Please help for error ( file <libxml/parser.h> is required for XML support )\r\n\r\nPackage libxml2-devel-2.9.1-6.el7.4.ppc64le is already installed.\r\n\r\nThanks and Regards,\r\nSACHIN KHANNA\r\n212 BASIS DBA TEAM OFFSHORE\r\nOffice : 204058624\r\nCell : 9049522511\r\n\r\nFrom: Ranier Vilela <ranier.vf@gmail.com<mailto:ranier.vf@gmail.com>>\r\nSent: Thursday, August 27, 2020 6:46 PM\r\nTo: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org<mailto:pgsql-hackers@lists.postgresql.org>>\r\nCc: Sachin Khanna <Sachin_Khanna@infosys.com<mailto:Sachin_Khanna@infosys.com>>\r\nSubject: re: Please help for error ( file <libxml/parser.h> is required for XML support )\r\n\r\n\r\n[**EXTERNAL EMAIL**]\r\n>checking for libxml/parser.h... no\r\n>configure: error: header file <libxml/parser.h> is required for XML support\r\n\r\nsudo yum install libxml2-devel\r\n\r\nYou need to install the development package before ./configure.\r\n\r\nregards,\r\nRanier Vilela", "msg_date": "Fri, 28 Aug 2020 07:36:48 +0000", "msg_from": "Sachin Khanna <Sachin_Khanna@infosys.com>", "msg_from_op": false, "msg_subject": "RE: Please help for error ( file <libxml/parser.h> is required for\n XML support )" }, { "msg_contents": "Em sex., 28 de ago. de 2020 às 04:37, Sachin Khanna <\nSachin_Khanna@infosys.com> escreveu:\n\n>\n>\n> Now I can see the that libraries are identified in config.log . I also\n> found some error in configuration file as well. Highlight below.\n>\n> Please find the attached config.log file for reference.\n>\n> Please help and let me know if I there is any issue in configuration\n> script and I need to change it ?\n>\n>\n>\n> I am using PostgreSQL version postgresql-12.3.tar.gz\n>\n>\n>\n> configure:8291: checking for XML2_CONFIG\n>\n> configure:8293: result: /usr/lib64/libxml2.so\n>\n> configure:8416: checking for grep that handles long lines and -e\n>\n> configure:8474: result: /bin/grep\n>\n> configure:8479: checking for egrep\n>\n> configure:8541: result: /bin/grep -E\n>\n> configure:8588: checking for ld used by GCC\n>\n> configure:8651: result: /bin/ld\n>\n> configure:8658: checking if the linker (/bin/ld) is GNU ld\n>\n> GNU ld version 2.27-44.base.el7\n>\n>\n>\n> at-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2\n> -D_GNU_SOURCE conftest.c >&5\n>\n> conftest.c: In function 'main':\n>\n> *conftest.c:76:20: error: expected expression before ')' token*\n>\n> *if (sizeof ((_Bool)))*\n>\n> * ^*\n>\n> *configure:12910: $? = 1*\n>\n> *configure: failed program was:*\n>\n> *| /* confdefs.h */*\n>\nWhat version of gcc is being used in this environment?\n\nregards,\nRanier Vilela\n\nEm sex., 28 de ago. de 2020 às 04:37, Sachin Khanna <Sachin_Khanna@infosys.com> escreveu:\n\n\n \nNow I can see the that libraries are identified in config.log . I also found some error in configuration file as well. Highlight below.\n\nPlease find the attached config.log file for reference. \n\nPlease help and let me know if I there is any issue in configuration script and I need to change it ?\n \nI am using PostgreSQL version postgresql-12.3.tar.gz\n \nconfigure:8291: checking for XML2_CONFIG\nconfigure:8293: result: /usr/lib64/libxml2.so\nconfigure:8416: checking for grep that handles long lines and -e\nconfigure:8474: result: /bin/grep\nconfigure:8479: checking for egrep\nconfigure:8541: result: /bin/grep -E\nconfigure:8588: checking for ld used by GCC\nconfigure:8651: result: /bin/ld\nconfigure:8658: checking if the linker (/bin/ld) is GNU ld\nGNU ld version 2.27-44.base.el7\n \nat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2  -D_GNU_SOURCE  conftest.c >&5\nconftest.c: In function 'main':\nconftest.c:76:20: error: expected expression before ')' token\nif (sizeof ((_Bool)))\n                    ^\nconfigure:12910: $? = 1\nconfigure: failed program was:\n| /* confdefs.h */What version of gcc is being used in this environment?regards,Ranier Vilela", "msg_date": "Fri, 28 Aug 2020 11:05:50 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Please help for error ( file <libxml/parser.h> is required for\n XML support )" }, { "msg_contents": "em sex., 28 de ago. de 2020 às 11:05, Ranier Vilela <ranier.vf@gmail.com>\nescreveu:\n\n> Em sex., 28 de ago. de 2020 às 04:37, Sachin Khanna <\n> Sachin_Khanna@infosys.com> escreveu:\n>\n>>\n>>\n>> Now I can see the that libraries are identified in config.log . I also\n>> found some error in configuration file as well. Highlight below.\n>>\n>> Please find the attached config.log file for reference.\n>>\n>> Please help and let me know if I there is any issue in configuration\n>> script and I need to change it ?\n>>\n>>\n>>\n>> I am using PostgreSQL version postgresql-12.3.tar.gz\n>>\n>>\n>>\n>> configure:8291: checking for XML2_CONFIG\n>>\n>> configure:8293: result: /usr/lib64/libxml2.so\n>>\n>> configure:8416: checking for grep that handles long lines and -e\n>>\n>> configure:8474: result: /bin/grep\n>>\n>> configure:8479: checking for egrep\n>>\n>> configure:8541: result: /bin/grep -E\n>>\n>> configure:8588: checking for ld used by GCC\n>>\n>> configure:8651: result: /bin/ld\n>>\n>> configure:8658: checking if the linker (/bin/ld) is GNU ld\n>>\n>> GNU ld version 2.27-44.base.el7\n>>\n>>\n>>\n>> at-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2\n>> -D_GNU_SOURCE conftest.c >&5\n>>\n>> conftest.c: In function 'main':\n>>\n>> *conftest.c:76:20: error: expected expression before ')' token*\n>>\n>> *if (sizeof ((_Bool)))*\n>>\n>> * ^*\n>>\n>> *configure:12910: $? = 1*\n>>\n>> *configure: failed program was:*\n>>\n>> *| /* confdefs.h */*\n>>\n> What version of gcc is being used in this environment?\n>\nIt seems gcc does not compile C99, without -std=c99\nconfigure:4421: checking for gcc option to accept ISO C99\nconftest.c:130:3: note: use option -std=c99 or -std=gnu99 to compile your\ncode\n\ntry add -std=c99\n./configure -std=c99\n\nregards,\nRanier Vilela\n\nem sex., 28 de ago. de 2020 às 11:05, Ranier Vilela <ranier.vf@gmail.com> escreveu:Em sex., 28 de ago. de 2020 às 04:37, Sachin Khanna <Sachin_Khanna@infosys.com> escreveu:\n\n\n \nNow I can see the that libraries are identified in config.log . I also found some error in configuration file as well. Highlight below.\n\nPlease find the attached config.log file for reference. \n\nPlease help and let me know if I there is any issue in configuration script and I need to change it ?\n \nI am using PostgreSQL version postgresql-12.3.tar.gz\n \nconfigure:8291: checking for XML2_CONFIG\nconfigure:8293: result: /usr/lib64/libxml2.so\nconfigure:8416: checking for grep that handles long lines and -e\nconfigure:8474: result: /bin/grep\nconfigure:8479: checking for egrep\nconfigure:8541: result: /bin/grep -E\nconfigure:8588: checking for ld used by GCC\nconfigure:8651: result: /bin/ld\nconfigure:8658: checking if the linker (/bin/ld) is GNU ld\nGNU ld version 2.27-44.base.el7\n \nat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2  -D_GNU_SOURCE  conftest.c >&5\nconftest.c: In function 'main':\nconftest.c:76:20: error: expected expression before ')' token\nif (sizeof ((_Bool)))\n                    ^\nconfigure:12910: $? = 1\nconfigure: failed program was:\n| /* confdefs.h */What version of gcc is being used in this environment?It seems gcc does not compile C99, without -std=c99configure:4421: checking for gcc option to accept ISO C99conftest.c:130:3: note: use option -std=c99 or -std=gnu99 to compile your codetry add -std=c99./configure -std=c99regards,Ranier Vilela", "msg_date": "Fri, 28 Aug 2020 11:13:28 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Please help for error ( file <libxml/parser.h> is required for\n XML support )" } ]
[ { "msg_contents": "Hi all,\n\nthis minor patch is attempting to force the use of the tableam api in dbsize where ever it is required.\n\nApparently something similar was introduced for toast relations only. Intuitively it seems that the distinction between a table and a toast table is not needed. This patch treats tables, toast tables and materialized views equally.\n\nRegards,\n//Georgios", "msg_date": "Thu, 27 Aug 2020 13:38:51 +0000", "msg_from": "gkokolatos@pm.me", "msg_from_op": true, "msg_subject": "PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": "On Thu, Aug 27, 2020 at 9:39 AM <gkokolatos@pm.me> wrote:\n>\n> Hi all,\n>\n> this minor patch is attempting to force the use of the tableam api in dbsize where ever it is required.\n>\n> Apparently something similar was introduced for toast relations only. Intuitively it seems that the distinction between a table and a toast table is not needed.\n\nI suspect the reason is found in the comment for table_block_relation_size():\n\n * If a table AM uses the various relation forks as the sole place where data\n * is stored, and if it uses them in the expected manner (e.g. the actual data\n * is in the main fork rather than some other), it can use this implementation\n * of the relation_size callback rather than implementing its own.\n\n-- \nJohn Naylor https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 8 Sep 2020 09:49:41 -0400", "msg_from": "John Naylor <john.naylor@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": "\nI found the function \"table_relation_size\" is only used by buffer \nmanager for \"RELKIND_RELATION\", \"RELKIND_TOASTVALUE\" and \n\"RELKIND_MATVIEW\", i.e.\n\n         case RELKIND_RELATION:\n         case RELKIND_TOASTVALUE:\n         case RELKIND_MATVIEW:\n             {\n                 /*\n                  * Not every table AM uses BLCKSZ wide fixed size blocks.\n                  * Therefore tableam returns the size in bytes - but \nfor the\n                  * purpose of this routine, we want the number of blocks.\n                  * Therefore divide, rounding up.\n                  */\n                 uint64        szbytes;\n\n                 szbytes = table_relation_size(relation, forkNum);\n\n                 return (szbytes + (BLCKSZ - 1)) / BLCKSZ;\n             }\n\nSo using \"calculate_relation_size\" and \"calculate_toast_table_size\" in \n\"calculate_table_size\" is easy to understand and the original logic is \nsimple.\n\n\nOn 2020-08-27 6:38 a.m., gkokolatos@pm.me wrote:\n> Hi all,\n>\n> this minor patch is attempting to force the use of the tableam api in dbsize where ever it is required.\n>\n> Apparently something similar was introduced for toast relations only. Intuitively it seems that the distinction between a table and a toast table is not needed. This patch treats tables, toast tables and materialized views equally.\n>\n> Regards,\n> //Georgios\nBest regards,\n-- \nDavid\n\nSoftware Engineer\nHighgo Software Inc. (Canada)\nwww.highgo.ca\n\n\n\n", "msg_date": "Tue, 8 Sep 2020 12:26:19 -0700", "msg_from": "David Zhang <david.zhang@highgo.ca>", "msg_from_op": false, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": "\n\n\n\n\n‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn Tuesday, 8 September 2020 16:49, John Naylor <john.naylor@2ndquadrant.com> wrote:\n\n> On Thu, Aug 27, 2020 at 9:39 AM gkokolatos@pm.me wrote:\n>\n> > Hi all,\n> > this minor patch is attempting to force the use of the tableam api in dbsize where ever it is required.\n> > Apparently something similar was introduced for toast relations only. Intuitively it seems that the distinction between a table and a toast table is not needed.\n>\n> I suspect the reason is found in the comment for table_block_relation_size():\n>\n> - If a table AM uses the various relation forks as the sole place where data\n> - is stored, and if it uses them in the expected manner (e.g. the actual data\n> - is in the main fork rather than some other), it can use this implementation\n> - of the relation_size callback rather than implementing its own.\n\n\nThank you for your answer and interest at the patch.\n\nI agree with the comment above. However I do not see why it is relevant here. When issuing:\n\nSELECT pg_table_size('foo'::regclass);\n\nI should not have to care about the on disk layout of the relation 'foo'.\nWithout this patch, one will get a correct result only when 'foo' is a heap table.\nFor custom layouts the result can potentially be wrong.\n\n\n\n>\n> --\n> John Naylor https://www.2ndQuadrant.com/\n> PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n>\n\n\n\n\n", "msg_date": "Wed, 09 Sep 2020 07:36:21 +0000", "msg_from": "gkokolatos@pm.me", "msg_from_op": true, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": "\n\n\n\n\n‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn Tuesday, 8 September 2020 22:26, David Zhang <david.zhang@highgo.ca> wrote:\n\n>\n>\n> I found the function \"table_relation_size\" is only used by buffer\n> manager for \"RELKIND_RELATION\", \"RELKIND_TOASTVALUE\" and\n> \"RELKIND_MATVIEW\", i.e.\n>\n>         case RELKIND_RELATION:\n>         case RELKIND_TOASTVALUE:\n>         case RELKIND_MATVIEW:\n>             {\n>                 /*\n>                  * Not every table AM uses BLCKSZ wide fixed size blocks.\n>                  * Therefore tableam returns the size in bytes - but\n> for the\n>                  * purpose of this routine, we want the number of blocks.\n>                  * Therefore divide, rounding up.\n>                  */\n>                 uint64        szbytes;\n>\n>                 szbytes = table_relation_size(relation, forkNum);\n>\n>                 return (szbytes + (BLCKSZ - 1)) / BLCKSZ;\n>             }\n>\n> So using \"calculate_relation_size\" and \"calculate_toast_table_size\" in\n> \"calculate_table_size\" is easy to understand and the original logic is\n> simple.\n>\n\nYou are correct. This is the logic that is attempted to be applied\nin dbsize.c in this patch.\n\nSo what do you think of the patch?\n\n\n", "msg_date": "Wed, 09 Sep 2020 07:41:17 +0000", "msg_from": "gkokolatos@pm.me", "msg_from_op": true, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": "\nOn 2020-09-09 12:41 a.m., gkokolatos@pm.me wrote:\n> ‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\n> On Tuesday, 8 September 2020 22:26, David Zhang <david.zhang@highgo.ca> wrote:\n>\n>>\n>> I found the function \"table_relation_size\" is only used by buffer\n>> manager for \"RELKIND_RELATION\", \"RELKIND_TOASTVALUE\" and\n>> \"RELKIND_MATVIEW\", i.e.\n>>\n>>         case RELKIND_RELATION:\n>>         case RELKIND_TOASTVALUE:\n>>         case RELKIND_MATVIEW:\n>>             {\n>>                 /*\n>>                  * Not every table AM uses BLCKSZ wide fixed size blocks.\n>>                  * Therefore tableam returns the size in bytes - but\n>> for the\n>>                  * purpose of this routine, we want the number of blocks.\n>>                  * Therefore divide, rounding up.\n>>                  */\n>>                 uint64        szbytes;\n>>\n>>                 szbytes = table_relation_size(relation, forkNum);\n>>\n>>                 return (szbytes + (BLCKSZ - 1)) / BLCKSZ;\n>>             }\n>>\n>> So using \"calculate_relation_size\" and \"calculate_toast_table_size\" in\n>> \"calculate_table_size\" is easy to understand and the original logic is\n>> simple.\n>>\n> You are correct. This is the logic that is attempted to be applied\n> in dbsize.c in this patch.\n>\n> So what do you think of the patch?\n\nI would suggest to keep the original logic unless there is a bug.\n\n-- \nDavid\n\nSoftware Engineer\nHighgo Software Inc. (Canada)\nwww.highgo.ca\n\n\n\n", "msg_date": "Wed, 9 Sep 2020 22:36:45 -0700", "msg_from": "David Zhang <david.zhang@highgo.ca>", "msg_from_op": false, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": ">> So what do you think of the patch?\n> \n> I would suggest to keep the original logic unless there is a bug.\n\nIIUC, the premise of this path submission is that this codepath is in fact\nbuggy as it may lead to incorrect results for non-heap relations?\n\nSince we have introduced the table AM api I support going throug it for all\ntable accesses, so +1 on the overall idea.\n\nSome comments on the patch:\n\n- * Note that this also behaves sanely if applied to an index or toast table;\n+ * Note that this also behaves sanely if applied to a toast table;\n * those won't have attached toast tables, but they can have multiple forks.\nThis comment reads a bit odd now and should probably be reworded.\n\n\n- return size;\n+ Assert(size < PG_INT64_MAX);\n+\n+ return (int64)size;\nI assume that this change, and the other ones like that, aim to handle int64\noverflow? Using the extra legroom of uint64 can still lead to an overflow,\nhowever theoretical it may be. Wouldn't it be better to check for overflow\nbefore adding to size rather than after the fact? Something along the lines of\nchecking for headroom left:\n\n rel_size = table_relation_size(..);\n if (rel_size > (PG_INT64_MAX - total_size))\n < error codepath >\n total_size += rel_size;\n\n\n+ if (rel->rd_rel->relkind != RELKIND_INDEX)\n+ {\n+ relation_close(rel, AccessShareLock);\n+ PG_RETURN_NULL();\n+ }\npg_indexes_size is defined as returning the size of the indexes attached to the\nspecified relation, so this hunk is wrong as it instead requires rel to be an\nindex?\n\ncheers ./daniel\n\n", "msg_date": "Thu, 10 Sep 2020 11:51:30 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": "On Thu, Sep 10, 2020 at 11:51:30AM +0200, Daniel Gustafsson wrote:\n> Some comments on the patch:\n\nExtra comment for this patch: regression tests are failing.\n--\nMichael", "msg_date": "Thu, 24 Sep 2020 13:20:40 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": "‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn Thursday, September 10, 2020 12:51 PM, Daniel Gustafsson <daniel@yesql.se> wrote:\n\n[snip]\n\n> Since we have introduced the table AM api I support going throug it for all\n> table accesses, so +1 on the overall idea.\n>\n\nThank you for reviewing! Please find v2 of the patch attached.\n\nIn addition to addressing the comments, this patch contains a slightly opinionated approach during describe. In short, only relations that have storage, are returning non null size during when \\d*+ commands are emitted. Such an example is a view which can be found in the psql tests. If a view was returning a size of 0 Bytes, it would indicate that it can potentially be non zero, which is of course wrong.\n\n\n> Some comments on the patch:\n>\n> - - Note that this also behaves sanely if applied to an index or toast table;\n>\n> - - Note that this also behaves sanely if applied to a toast table;\n> - those won't have attached toast tables, but they can have multiple forks.\n> This comment reads a bit odd now and should probably be reworded.\n>\n\nAgreed and amended.\n\n>\n> - return size;\n>\n> - Assert(size < PG_INT64_MAX);\n>\n> -\n> - return (int64)size;\n> I assume that this change, and the other ones like that, aim to handle int64\n> overflow? Using the extra legroom of uint64 can still lead to an overflow,\n> however theoretical it may be. Wouldn't it be better to check for overflow\n> before adding to size rather than after the fact? Something along the lines of\n> checking for headroom left:\n>\n> rel_size = table_relation_size(..);\n> if (rel_size > (PG_INT64_MAX - total_size))\n> < error codepath >\n>\n>\n> total_size += rel_size;\n\nActually not, the intention is not to handle overflow. The table_relation_size() returns a uint64 and the calling function returns int64.\n\nThe Assert() has been placed in order to denote that it is acknowledged that the two functions return different types. I was of the opinion that a run time check will not be needed as even the smaller type can cover more than 9200 PetaByte tables.\n\nIf we were to change anything, then I would prefer to change the signature of the pg_*_size family of functions to return uint64 instead.\n\n\n>\n> - if (rel->rd_rel->relkind != RELKIND_INDEX)\n>\n> - {\n>\n> - relation_close(rel, AccessShareLock);\n>\n>\n> - PG_RETURN_NULL();\n>\n>\n> - }\n> pg_indexes_size is defined as returning the size of the indexes attached to the\n> specified relation, so this hunk is wrong as it instead requires rel to be an\n> index?\n\nYou are absolutely correct, amended.\n\n>\n> cheers ./daniel\n>", "msg_date": "Tue, 13 Oct 2020 13:28:02 +0000", "msg_from": "gkokolatos@pm.me", "msg_from_op": true, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": "Hey Georgios,\n\nThanks for looking for more avenues to invoke tableAM APIS! Please find\nmy review below:\n\nOn Tue, Oct 13, 2020 at 6:28 AM <gkokolatos@pm.me> wrote:\n\n1.\n\n> /*\n> - * heap size, including FSM and VM\n> + * table size, including FSM and VM\n> */\n\nWe should not mention FSM and VM in dbsize.c at all as these are\nheap AM specific. We can say:\ntable size, excluding TOAST relation\n\n2.\n\n> /*\n> * Size of toast relation\n> */\n> if (OidIsValid(rel->rd_rel->reltoastrelid))\n> - size += calculate_toast_table_size(rel->rd_rel->reltoastrelid);\n> + {\n> + Relation toastRel;\n> +\n> + toastRel = relation_open(rel->rd_rel->reltoastrelid, AccessShareLock);\n\nWe can replace the OidIsValid check with relation_needs_toast_table()\nand then have the OidIsValid() check in an Assert. Perhaps, that will\nmake things more readable.\n\n3.\n\n> + if (rel->rd_rel->relkind == RELKIND_RELATION ||\n> + rel->rd_rel->relkind == RELKIND_TOASTVALUE ||\n> + rel->rd_rel->relkind == RELKIND_MATVIEW)\n> + size = calculate_table_size(rel);\n> + else\n> + {\n> + relation_close(rel, AccessShareLock);\n> + PG_RETURN_NULL();\n> + }\n\nThis leads to behavioral changes:\n\nI am talking about the case where one calls pg_table_size() on an index.\nW/o your patch, it returns the size of the index. W/ your patch it\nreturns NULL. Judging by the documentation, this function should not\nideally apply to indexes but it does! I have a sinking feeling that lots\nof users use it for this purpose, as there is no function to calculate\nthe size of a single specific index (except pg_relation_size()).\nThe same argument I have made above applies to sequences. Users may have\ntrial-and-errored their way into finding that pg_table_size() can tell\nthem the size of a specific index/sequence! I don't know how widespread\nthe use is in the user community, so IMO maybe we should be conservative\nand not introduce this change? Alternatively, we could call out that\npg_table_size() is only for tables by throwing an error if anything\nother than a table is passed in.\n\nIf we decide to preserve the existing behavior of the pg_table_size():\nIt seems that for things not backed by the tableAM (indexes and\nsequences), they should still go through calculate_relation_size().\nWe can call table_relation_size() based on if relkind is\nRELKIND_RELATION, RELKIND_TOASTVALUE or RELKIND_MATVIEW. Perhaps it\nmight be worthwhile making a new macro RELKIND_HAS_TABLE_STORAGE to\ncapture these three cases (See RELKIND_HAS_STORAGE). This also ensures\nthat we return 0 for things that don't qualify as RELKIND_HAS_STORAGE,\nsuch as a partitioned table (Currently w/ the patch applied, we return\nNULL for those cases, which is another behavior change)\n\n4.\n\n> @@ -3776,10 +3776,24 @@ listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSys\n> gettext_noop(\"Access Method\"));\n>\n> /*\n> + * As of PostgreSQL 14, do not use pg_table_size() for indexes and\n> + * sequences as it does not behave sanely for those.\n> + *\n> * As of PostgreSQL 9.0, use pg_table_size() to show a more accurate\n> * size of a table, including FSM, VM and TOAST tables.\n> */\n> - if (pset.sversion >= 90000)\n> + if (pset.sversion >= 140000)\n> + appendPQExpBuffer(&buf,\n> + \",\\n CASE\"\n> + \" WHEN c.relkind in (\"CppAsString2(RELKIND_INDEX)\", \"\n> + CppAsString2(RELKIND_PARTITIONED_INDEX)\", \"\n> + CppAsString2(RELKIND_SEQUENCE)\") THEN\"\n> + \" pg_catalog.pg_size_pretty(pg_catalog.pg_relation_size(c.oid))\"\n> + \" ELSE\"\n> + \" pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid))\"\n> + \" END as \\\"%s\\\"\",\n> + gettext_noop(\"Size\"));\n> + else if (pset.sversion >= 90000)\n> appendPQExpBuffer(&buf,\n> \",\\n pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid)) as \\\"%s\\\"\",\n> gettext_noop(\"Size\"));\n\nFollowing on from point 3, if we decide to preserve the existing behavior,\nwe wouldn't need this change, as it would be internalized within\npg_table_size().\n\n\n4.\n> >\n> > - return size;\n> >\n> > - Assert(size < PG_INT64_MAX);\n> >\n> > -\n> > - return (int64)size;\n> > I assume that this change, and the other ones like that, aim to handle int64\n> > overflow? Using the extra legroom of uint64 can still lead to an overflow,\n> > however theoretical it may be. Wouldn't it be better to check for overflow\n> > before adding to size rather than after the fact? Something along the lines of\n> > checking for headroom left:\n> >\n> > rel_size = table_relation_size(..);\n> > if (rel_size > (PG_INT64_MAX - total_size))\n> > < error codepath >\n> >\n> >\n> > total_size += rel_size;\n>\n>\n>\n> Actually not, the intention is not to handle overflow. The table_relation_size() returns a uint64 and the calling function returns int64.\n>\n>\n>\n> The Assert() has been placed in order to denote that it is acknowledged that the two functions return different types. I was of the opinion that a run time check will not be needed as even the > smaller type can cover more than 9200 PetaByte tables.\n>\n>\n>\n> If we were to change anything, then I would prefer to change the signature of the pg_*_size family of functions to return uint64 instead.\n\nChanging the signature would be the ideal change for all of this here.\nBut Postgres does not have support for an unsigned 64bit integer (bigint\nis signed). One would need to turn to extensions such as [1]. Thus, +1\nto what Daniel said above.\n\n\n5.\n> @@ -415,7 +384,7 @@ calculate_table_size(Relation rel)\n> static int64\n> calculate_indexes_size(Relation rel)\n> {\n> - int64 size = 0;\n> + uint64 size = 0;\n>\n> /*\n> * Aggregate all indexes on the given relation\n> @@ -444,7 +413,9 @@ calculate_indexes_size(Relation rel)\n> list_free(index_oids);\n> }\n>\n> - return size;\n> + Assert(size < PG_INT64_MAX);\n> +\n> + return (int64)size;\n> }\n\nI don't think we would need these changes as nothing changed in this\nfunction.\n\nRegards,\nSoumyadeep\n\n[1] https://github.com/petere/pguint\n\n\n", "msg_date": "Mon, 9 Nov 2020 10:50:25 -0800", "msg_from": "Soumyadeep Chakraborty <soumyadeep2007@gmail.com>", "msg_from_op": false, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": "\n\n\n\n\n‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn Monday, November 9, 2020 7:50 PM, Soumyadeep Chakraborty <soumyadeep2007@gmail.com> wrote:\n\n> Hey Georgios,\n>\n> Thanks for looking for more avenues to invoke tableAM APIS! Please find\n> my review below:\n\nA great review Soumyadeep, it is much appreciated.\nPlease remember to add yourself as a reviewer in the commitfest\n[https://commitfest.postgresql.org/30/2701/]\n\n>\n> On Tue, Oct 13, 2020 at 6:28 AM gkokolatos@pm.me wrote:\n>\n> 1.\n>\n> > /*\n> >\n> > - - heap size, including FSM and VM\n> >\n> > - - table size, including FSM and VM\n> > */\n> >\n>\n> We should not mention FSM and VM in dbsize.c at all as these are\n> heap AM specific. We can say:\n> table size, excluding TOAST relation\n\nYeah, I was thinking that the notion that FSM and VM are still taken\ninto account should be stated. We are iterating over ForkNumber\nafter all.\n\nHow about phrasing it as:\n\n+ table size, including all implemented forks from the AM (e.g. FSM, VM)\n+ excluding TOAST relations\n\nThoughts?\n\n>\n> 2.\n>\n> > /*\n> >\n> > - Size of toast relation\n> > */\n> > if (OidIsValid(rel->rd_rel->reltoastrelid))\n> >\n> >\n> > - size += calculate_toast_table_size(rel->rd_rel->reltoastrelid);\n> >\n> > - {\n> > - Relation toastRel;\n> > -\n> > - toastRel = relation_open(rel->rd_rel->reltoastrelid, AccessShareLock);\n>\n> We can replace the OidIsValid check with relation_needs_toast_table()\n> and then have the OidIsValid() check in an Assert. Perhaps, that will\n> make things more readable.\n\nPlease, allow me to kindly disagree.\n\nRelation is already open at this stage. Even create_toast_table(), the\ninternal workhorse for creating toast relations, does check reltoastrelid\nto test if the relation is already toasted.\n\nFurthermore, we do call:\n\n+ toastRel = relation_open(rel->rd_rel->reltoastrelid, AccessShareLock);\n\nand in order to avoid elog() errors underneath us, we ought to have\nverified the validity of reltoastrelid.\n\nIn short, I think that the code in the proposal is not too unreadable\nnor that it breaks the coding patterns throughout the codebase.\n\nAm I too wrong?\n\n>\n> 3.\n>\n> > - if (rel->rd_rel->relkind == RELKIND_RELATION ||\n> > - rel->rd_rel->relkind == RELKIND_TOASTVALUE ||\n> > - rel->rd_rel->relkind == RELKIND_MATVIEW)\n> > - size = calculate_table_size(rel);\n> > - else\n> > - {\n> > - relation_close(rel, AccessShareLock);\n> > - PG_RETURN_NULL();\n> > - }\n>\n> This leads to behavioral changes:\n>\n> I am talking about the case where one calls pg_table_size() on an index.\n> W/o your patch, it returns the size of the index. W/ your patch it\n> returns NULL. Judging by the documentation, this function should not\n> ideally apply to indexes but it does! I have a sinking feeling that lots\n> of users use it for this purpose, as there is no function to calculate\n> the size of a single specific index (except pg_relation_size()).\n> The same argument I have made above applies to sequences. Users may have\n> trial-and-errored their way into finding that pg_table_size() can tell\n> them the size of a specific index/sequence! I don't know how widespread\n> the use is in the user community, so IMO maybe we should be conservative\n> and not introduce this change? Alternatively, we could call out that\n> pg_table_size() is only for tables by throwing an error if anything\n> other than a table is passed in.\n>\n> If we decide to preserve the existing behavior of the pg_table_size():\n> It seems that for things not backed by the tableAM (indexes and\n> sequences), they should still go through calculate_relation_size().\n> We can call table_relation_size() based on if relkind is\n> RELKIND_RELATION, RELKIND_TOASTVALUE or RELKIND_MATVIEW. Perhaps it\n> might be worthwhile making a new macro RELKIND_HAS_TABLE_STORAGE to\n> capture these three cases (See RELKIND_HAS_STORAGE). This also ensures\n> that we return 0 for things that don't qualify as RELKIND_HAS_STORAGE,\n> such as a partitioned table (Currently w/ the patch applied, we return\n> NULL for those cases, which is another behavior change)\n\n\nExcellent point. This is the discussion I was longing to have.\n\nI stand by the decision coded in the patch, that pg_table_size() should\nreturn NULL for other kinds of relations, such as indexes, sequences\netc.\n\nIt is a conscious decision based on the following:\n\n * Supported by the documentation, pg_table_size() applies to tables only.\nFor other uses the higher-level functions pg_total_relation_size() or\npg_relation_size() should be used.\n * Commit fa352d662e taught pg_relation_size() and friends to return NULL if the object doesn't exist. This makes perfect sense for the\nscenarios described in the commit:\n\n That avoids errors when the functions are used in queries like\n \"SELECT pg_relation_size(oid) FROM pg_class\",\n and a table is dropped concurrently.\n\nIMHO: It is more consistent to return NULL when the relation does exist\nOR it is not a table kind.\n* Returning 0 for things that do not have storage, is nonsensical because\nit implies that it can be NON zero at some point. Things that do not\nhave storage have an unknown size.\n\n\nAs far as for the argument that users might have trialed and errored\ntheir way into undocumented behaviour, I do not think it is strong\nenough to stop us from implementing the documented behaviour.\n\n>\n> 4.\n>\n> > @@ -3776,10 +3776,24 @@ listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSys\n> > gettext_noop(\"Access Method\"));\n> >\n> > /*\n> >\n> >\n> > - * As of PostgreSQL 14, do not use pg_table_size() for indexes and\n> >\n> >\n> > - * sequences as it does not behave sanely for those.\n> >\n> >\n> > - *\n> > * As of PostgreSQL 9.0, use pg_table_size() to show a more accurate\n> > * size of a table, including FSM, VM and TOAST tables.\n> > */\n> >\n> >\n> >\n> > - if (pset.sversion >= 90000)\n> >\n> >\n> >\n> > - if (pset.sversion >= 140000)\n> >\n> >\n> > - appendPQExpBuffer(&buf,\n> >\n> >\n> > - \",\\\\n CASE\"\n> >\n> >\n> > - \" WHEN c.relkind in (\"CppAsString2(RELKIND_INDEX)\", \"\n> >\n> >\n> > - CppAsString2(RELKIND_PARTITIONED_INDEX)\", \"\n> >\n> >\n> > - CppAsString2(RELKIND_SEQUENCE)\") THEN\"\n> >\n> >\n> > - \" pg_catalog.pg_size_pretty(pg_catalog.pg_relation_size(c.oid))\"\n> >\n> >\n> > - \" ELSE\"\n> >\n> >\n> > - \" pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid))\"\n> >\n> >\n> > - \" END as \\\\\"%s\\\\\"\",\n> >\n> >\n> > - gettext_noop(\"Size\"));\n> >\n> >\n> > - else if (pset.sversion >= 90000)\n> > appendPQExpBuffer(&buf,\n> > \",\\\\n pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid)) as \\\\\"%s\\\\\"\",\n> > gettext_noop(\"Size\"));\n> >\n> >\n>\n> Following on from point 3, if we decide to preserve the existing behavior,\n> we wouldn't need this change, as it would be internalized within\n> pg_table_size().\n\nWe really should not decide to preserve the existing behaviour.\n\nI will reiterate my point: Returning 0 for things that do not have\nstorage, implies that it can be NON zero at some point. We should not\ntreat pg_table_size() as an alias for pg_relation_size().\n\n>\n> 4.\n>\n> > > - return size;\n> > >\n> > > - Assert(size < PG_INT64_MAX);\n> > >\n> > > -\n> > > - return (int64)size;\n> > > I assume that this change, and the other ones like that, aim to handle int64\n> > > overflow? Using the extra legroom of uint64 can still lead to an overflow,\n> > > however theoretical it may be. Wouldn't it be better to check for overflow\n> > > before adding to size rather than after the fact? Something along the lines of\n> > > checking for headroom left:\n> > > rel_size = table_relation_size(..);\n> > > if (rel_size > (PG_INT64_MAX - total_size))\n> > > < error codepath >\n> > >\n> > >\n> > > total_size += rel_size;\n> >\n> > Actually not, the intention is not to handle overflow. The table_relation_size() returns a uint64 and the calling function returns int64.\n> > The Assert() has been placed in order to denote that it is acknowledged that the two functions return different types. I was of the opinion that a run time check will not be needed as even the > smaller type can cover more than 9200 PetaByte tables.\n> > If we were to change anything, then I would prefer to change the signature of the pg_*_size family of functions to return uint64 instead.\n>\n> Changing the signature would be the ideal change for all of this here.\n> But Postgres does not have support for an unsigned 64bit integer (bigint\n> is signed). One would need to turn to extensions such as [1]. Thus, +1\n> to what Daniel said above.\n\nApologies, I do not follow. Are you suggesting that we should\nintroduce overflow tests?\n\n>\n> 5.\n>\n> > @@ -415,7 +384,7 @@ calculate_table_size(Relation rel)\n> > static int64\n> > calculate_indexes_size(Relation rel)\n> > {\n> >\n> > - int64 size = 0;\n> >\n> > - uint64 size = 0;\n> > /*\n> > - Aggregate all indexes on the given relation\n> > @@ -444,7 +413,9 @@ calculate_indexes_size(Relation rel)\n> > list_free(index_oids);\n> > }\n> >\n> >\n> > - return size;\n> >\n> > - Assert(size < PG_INT64_MAX);\n> > -\n> > - return (int64)size;\n> > }\n> >\n>\n> I don't think we would need these changes as nothing changed in this\n> function.\n\nThis change intended to keep the calculate family of functions\nhomogenous in style. From the point above I understand it confuses\nmore than helps, I will remove.\n\nCheers,\n//Georgios\n\n>\n> Regards,\n> Soumyadeep\n>\n> [1] https://github.com/petere/pguint\n\n\n\n\n", "msg_date": "Tue, 10 Nov 2020 14:19:06 +0000", "msg_from": "gkokolatos@pm.me", "msg_from_op": true, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": "Hey Georgios,\n\nOn Tue, Nov 10, 2020 at 6:20 AM <gkokolatos@pm.me> wrote:\n>\n>\n>\n>\n>\n>\n> ‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\n> On Monday, November 9, 2020 7:50 PM, Soumyadeep Chakraborty <soumyadeep2007@gmail.com> wrote:\n>\n> > Hey Georgios,\n> >\n> > Thanks for looking for more avenues to invoke tableAM APIS! Please find\n> > my review below:\n>\n> A great review Soumyadeep, it is much appreciated.\n> Please remember to add yourself as a reviewer in the commitfest\n> [https://commitfest.postgresql.org/30/2701/]\n\nAh yes. Sorry, I forgot that!\n\n> >\n> > On Tue, Oct 13, 2020 at 6:28 AM gkokolatos@pm.me wrote:\n> >\n> > 1.\n> >\n> > > /*\n> > >\n> > > - - heap size, including FSM and VM\n> > >\n> > > - - table size, including FSM and VM\n> > > */\n> > >\n> >\n> > We should not mention FSM and VM in dbsize.c at all as these are\n> > heap AM specific. We can say:\n> > table size, excluding TOAST relation\n>\n> Yeah, I was thinking that the notion that FSM and VM are still taken\n> into account should be stated. We are iterating over ForkNumber\n> after all.\n>\n> How about phrasing it as:\n>\n> + table size, including all implemented forks from the AM (e.g. FSM, VM)\n> + excluding TOAST relations\n>\n> Thoughts?\n\nYes, I was thinking along the same lines. The concept of a \"fork\" forced\nshould not be forced down into the tableAM. But that is a discussion for\nanother day. We can probably say:\n\n+ table size, including all implemented forks from the AM (e.g. FSM, VM\n+ for the heap AM) excluding TOAST relations\n\n> >\n> > 2.\n> >\n> > > /*\n> > >\n> > > - Size of toast relation\n> > > */\n> > > if (OidIsValid(rel->rd_rel->reltoastrelid))\n> > >\n> > >\n> > > - size += calculate_toast_table_size(rel->rd_rel->reltoastrelid);\n> > >\n> > > - {\n> > > - Relation toastRel;\n> > > -\n> > > - toastRel = relation_open(rel->rd_rel->reltoastrelid, AccessShareLock);\n> >\n> > We can replace the OidIsValid check with relation_needs_toast_table()\n> > and then have the OidIsValid() check in an Assert. Perhaps, that will\n> > make things more readable.\n>\n> Please, allow me to kindly disagree.\n>\n> Relation is already open at this stage. Even create_toast_table(), the\n> internal workhorse for creating toast relations, does check reltoastrelid\n> to test if the relation is already toasted.\n>\n> Furthermore, we do call:\n>\n> + toastRel = relation_open(rel->rd_rel->reltoastrelid, AccessShareLock);\n>\n> and in order to avoid elog() errors underneath us, we ought to have\n> verified the validity of reltoastrelid.\n>\n> In short, I think that the code in the proposal is not too unreadable\n> nor that it breaks the coding patterns throughout the codebase.\n>\n> Am I too wrong?\n\nNo not at all. The code in the proposal is indeed adhering to the\ncodebase. What I was going for here was to increase the usage of\nrelation_needs_toast_table(). What I meant was:\n\nif (table_relation_needs_toast_table(rel))\n{\nif (!OidIsValid(rel->rd_rel->reltoastrelid))\n{\nelog(ERROR, <errmsg that toast table wasn't found>);\n}\n//size calculation here..\n}\n\nWe want to error out if the toast table can't be found and the relation\nis expected to have one, which the existing code doesn't handle.\n\n\n>\n> >\n> > 3.\n> >\n> > > - if (rel->rd_rel->relkind == RELKIND_RELATION ||\n> > > - rel->rd_rel->relkind == RELKIND_TOASTVALUE ||\n> > > - rel->rd_rel->relkind == RELKIND_MATVIEW)\n> > > - size = calculate_table_size(rel);\n> > > - else\n> > > - {\n> > > - relation_close(rel, AccessShareLock);\n> > > - PG_RETURN_NULL();\n> > > - }\n> >\n> > This leads to behavioral changes:\n> >\n> > I am talking about the case where one calls pg_table_size() on an index.\n> > W/o your patch, it returns the size of the index. W/ your patch it\n> > returns NULL. Judging by the documentation, this function should not\n> > ideally apply to indexes but it does! I have a sinking feeling that lots\n> > of users use it for this purpose, as there is no function to calculate\n> > the size of a single specific index (except pg_relation_size()).\n> > The same argument I have made above applies to sequences. Users may have\n> > trial-and-errored their way into finding that pg_table_size() can tell\n> > them the size of a specific index/sequence! I don't know how widespread\n> > the use is in the user community, so IMO maybe we should be conservative\n> > and not introduce this change? Alternatively, we could call out that\n> > pg_table_size() is only for tables by throwing an error if anything\n> > other than a table is passed in.\n> >\n> > If we decide to preserve the existing behavior of the pg_table_size():\n> > It seems that for things not backed by the tableAM (indexes and\n> > sequences), they should still go through calculate_relation_size().\n> > We can call table_relation_size() based on if relkind is\n> > RELKIND_RELATION, RELKIND_TOASTVALUE or RELKIND_MATVIEW. Perhaps it\n> > might be worthwhile making a new macro RELKIND_HAS_TABLE_STORAGE to\n> > capture these three cases (See RELKIND_HAS_STORAGE). This also ensures\n> > that we return 0 for things that don't qualify as RELKIND_HAS_STORAGE,\n> > such as a partitioned table (Currently w/ the patch applied, we return\n> > NULL for those cases, which is another behavior change)\n>\n>\n> Excellent point. This is the discussion I was longing to have.\n>\n> I stand by the decision coded in the patch, that pg_table_size() should\n> return NULL for other kinds of relations, such as indexes, sequences\n> etc.\n>\n> It is a conscious decision based on the following:\n>\n> * Supported by the documentation, pg_table_size() applies to tables only.\n> For other uses the higher-level functions pg_total_relation_size() or\n> pg_relation_size() should be used.\n> * Commit fa352d662e taught pg_relation_size() and friends to return NULL if the object doesn't exist. This makes perfect sense for the\n> scenarios described in the commit:\n>\n> That avoids errors when the functions are used in queries like\n> \"SELECT pg_relation_size(oid) FROM pg_class\",\n> and a table is dropped concurrently.\n>\n> IMHO: It is more consistent to return NULL when the relation does exist\n> OR it is not a table kind.\n> * Returning 0 for things that do not have storage, is nonsensical because\n> it implies that it can be NON zero at some point. Things that do not\n> have storage have an unknown size.\n\nFair. We will have to document the behavior change.\n\n>\n> As far as for the argument that users might have trialed and errored\n> their way into undocumented behaviour, I do not think it is strong\n> enough to stop us from implementing the documented behaviour.\n\nFair. I would strongly vote for having two additional functions\n(pg_index_size() and pg_sequence_size()) to strongly signal our intent\nof banning that kind of use of pg_table_size(). I think it would help\nusers a lot. It is not easy to find what function to call when you want\nthe size of a single index/sequence.\n\n> >\n> > 4.\n> >\n> > > @@ -3776,10 +3776,24 @@ listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSys\n> > > gettext_noop(\"Access Method\"));\n> > >\n> > > /*\n> > >\n> > >\n> > > - * As of PostgreSQL 14, do not use pg_table_size() for indexes and\n> > >\n> > >\n> > > - * sequences as it does not behave sanely for those.\n> > >\n> > >\n> > > - *\n> > > * As of PostgreSQL 9.0, use pg_table_size() to show a more accurate\n> > > * size of a table, including FSM, VM and TOAST tables.\n> > > */\n> > >\n> > >\n> > >\n> > > - if (pset.sversion >= 90000)\n> > >\n> > >\n> > >\n> > > - if (pset.sversion >= 140000)\n> > >\n> > >\n> > > - appendPQExpBuffer(&buf,\n> > >\n> > >\n> > > - \",\\\\n CASE\"\n> > >\n> > >\n> > > - \" WHEN c.relkind in (\"CppAsString2(RELKIND_INDEX)\", \"\n> > >\n> > >\n> > > - CppAsString2(RELKIND_PARTITIONED_INDEX)\", \"\n> > >\n> > >\n> > > - CppAsString2(RELKIND_SEQUENCE)\") THEN\"\n> > >\n> > >\n> > > - \" pg_catalog.pg_size_pretty(pg_catalog.pg_relation_size(c.oid))\"\n> > >\n> > >\n> > > - \" ELSE\"\n> > >\n> > >\n> > > - \" pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid))\"\n> > >\n> > >\n> > > - \" END as \\\\\"%s\\\\\"\",\n> > >\n> > >\n> > > - gettext_noop(\"Size\"));\n> > >\n> > >\n> > > - else if (pset.sversion >= 90000)\n> > > appendPQExpBuffer(&buf,\n> > > \",\\\\n pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid)) as \\\\\"%s\\\\\"\",\n> > > gettext_noop(\"Size\"));\n> > >\n> > >\n> >\n> > Following on from point 3, if we decide to preserve the existing behavior,\n> > we wouldn't need this change, as it would be internalized within\n> > pg_table_size().\n>\n> We really should not decide to preserve the existing behaviour.\n>\n> I will reiterate my point: Returning 0 for things that do not have\n> storage, implies that it can be NON zero at some point. We should not\n> treat pg_table_size() as an alias for pg_relation_size().\n\n+1\n\n> >\n> > 4.\n> >\n> > > > - return size;\n> > > >\n> > > > - Assert(size < PG_INT64_MAX);\n> > > >\n> > > > -\n> > > > - return (int64)size;\n> > > > I assume that this change, and the other ones like that, aim to handle int64\n> > > > overflow? Using the extra legroom of uint64 can still lead to an overflow,\n> > > > however theoretical it may be. Wouldn't it be better to check for overflow\n> > > > before adding to size rather than after the fact? Something along the lines of\n> > > > checking for headroom left:\n> > > > rel_size = table_relation_size(..);\n> > > > if (rel_size > (PG_INT64_MAX - total_size))\n> > > > < error codepath >\n> > > >\n> > > >\n> > > > total_size += rel_size;\n> > >\n> > > Actually not, the intention is not to handle overflow. The table_relation_size() returns a uint64 and the calling function returns int64.\n> > > The Assert() has been placed in order to denote that it is acknowledged that the two functions return different types. I was of the opinion that a run time check will not be needed as even the > smaller type can cover more than 9200 PetaByte tables.\n> > > If we were to change anything, then I would prefer to change the signature of the pg_*_size family of functions to return uint64 instead.\n> >\n> > Changing the signature would be the ideal change for all of this here.\n> > But Postgres does not have support for an unsigned 64bit integer (bigint\n> > is signed). One would need to turn to extensions such as [1]. Thus, +1\n> > to what Daniel said above.\n>\n> Apologies, I do not follow. Are you suggesting that we should\n> introduce overflow tests?\n\nYes, to introduce the same overflow test that Daniel suggested above as\nreturning a uint64 in PG does not really return a uint64 AFAIU (since\nthe pg_**size() functions all return bigint which is signed and there\nis no uint64 user-facing type).\n\n\nRegards,\nSoumyadeep (VMware)\n\n\n", "msg_date": "Wed, 11 Nov 2020 09:53:48 -0800", "msg_from": "Soumyadeep Chakraborty <soumyadeep2007@gmail.com>", "msg_from_op": false, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": "On Thu, Nov 12, 2020 at 2:54 AM Soumyadeep Chakraborty\n<soumyadeep2007@gmail.com> wrote:\n>\n> Hey Georgios,\n>\n> On Tue, Nov 10, 2020 at 6:20 AM <gkokolatos@pm.me> wrote:\n> >\n> >\n> >\n> >\n> >\n> >\n> > ‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\n> > On Monday, November 9, 2020 7:50 PM, Soumyadeep Chakraborty <soumyadeep2007@gmail.com> wrote:\n> >\n> > > Hey Georgios,\n> > >\n> > > Thanks for looking for more avenues to invoke tableAM APIS! Please find\n> > > my review below:\n> >\n> > A great review Soumyadeep, it is much appreciated.\n> > Please remember to add yourself as a reviewer in the commitfest\n> > [https://commitfest.postgresql.org/30/2701/]\n>\n> Ah yes. Sorry, I forgot that!\n>\n> > >\n> > > On Tue, Oct 13, 2020 at 6:28 AM gkokolatos@pm.me wrote:\n> > >\n> > > 1.\n> > >\n> > > > /*\n> > > >\n> > > > - - heap size, including FSM and VM\n> > > >\n> > > > - - table size, including FSM and VM\n> > > > */\n> > > >\n> > >\n> > > We should not mention FSM and VM in dbsize.c at all as these are\n> > > heap AM specific. We can say:\n> > > table size, excluding TOAST relation\n> >\n> > Yeah, I was thinking that the notion that FSM and VM are still taken\n> > into account should be stated. We are iterating over ForkNumber\n> > after all.\n> >\n> > How about phrasing it as:\n> >\n> > + table size, including all implemented forks from the AM (e.g. FSM, VM)\n> > + excluding TOAST relations\n> >\n> > Thoughts?\n>\n> Yes, I was thinking along the same lines. The concept of a \"fork\" forced\n> should not be forced down into the tableAM. But that is a discussion for\n> another day. We can probably say:\n>\n> + table size, including all implemented forks from the AM (e.g. FSM, VM\n> + for the heap AM) excluding TOAST relations\n>\n> > >\n> > > 2.\n> > >\n> > > > /*\n> > > >\n> > > > - Size of toast relation\n> > > > */\n> > > > if (OidIsValid(rel->rd_rel->reltoastrelid))\n> > > >\n> > > >\n> > > > - size += calculate_toast_table_size(rel->rd_rel->reltoastrelid);\n> > > >\n> > > > - {\n> > > > - Relation toastRel;\n> > > > -\n> > > > - toastRel = relation_open(rel->rd_rel->reltoastrelid, AccessShareLock);\n> > >\n> > > We can replace the OidIsValid check with relation_needs_toast_table()\n> > > and then have the OidIsValid() check in an Assert. Perhaps, that will\n> > > make things more readable.\n> >\n> > Please, allow me to kindly disagree.\n> >\n> > Relation is already open at this stage. Even create_toast_table(), the\n> > internal workhorse for creating toast relations, does check reltoastrelid\n> > to test if the relation is already toasted.\n> >\n> > Furthermore, we do call:\n> >\n> > + toastRel = relation_open(rel->rd_rel->reltoastrelid, AccessShareLock);\n> >\n> > and in order to avoid elog() errors underneath us, we ought to have\n> > verified the validity of reltoastrelid.\n> >\n> > In short, I think that the code in the proposal is not too unreadable\n> > nor that it breaks the coding patterns throughout the codebase.\n> >\n> > Am I too wrong?\n>\n> No not at all. The code in the proposal is indeed adhering to the\n> codebase. What I was going for here was to increase the usage of\n> relation_needs_toast_table(). What I meant was:\n>\n> if (table_relation_needs_toast_table(rel))\n> {\n> if (!OidIsValid(rel->rd_rel->reltoastrelid))\n> {\n> elog(ERROR, <errmsg that toast table wasn't found>);\n> }\n> //size calculation here..\n> }\n>\n> We want to error out if the toast table can't be found and the relation\n> is expected to have one, which the existing code doesn't handle.\n>\n>\n> >\n> > >\n> > > 3.\n> > >\n> > > > - if (rel->rd_rel->relkind == RELKIND_RELATION ||\n> > > > - rel->rd_rel->relkind == RELKIND_TOASTVALUE ||\n> > > > - rel->rd_rel->relkind == RELKIND_MATVIEW)\n> > > > - size = calculate_table_size(rel);\n> > > > - else\n> > > > - {\n> > > > - relation_close(rel, AccessShareLock);\n> > > > - PG_RETURN_NULL();\n> > > > - }\n> > >\n> > > This leads to behavioral changes:\n> > >\n> > > I am talking about the case where one calls pg_table_size() on an index.\n> > > W/o your patch, it returns the size of the index. W/ your patch it\n> > > returns NULL. Judging by the documentation, this function should not\n> > > ideally apply to indexes but it does! I have a sinking feeling that lots\n> > > of users use it for this purpose, as there is no function to calculate\n> > > the size of a single specific index (except pg_relation_size()).\n> > > The same argument I have made above applies to sequences. Users may have\n> > > trial-and-errored their way into finding that pg_table_size() can tell\n> > > them the size of a specific index/sequence! I don't know how widespread\n> > > the use is in the user community, so IMO maybe we should be conservative\n> > > and not introduce this change? Alternatively, we could call out that\n> > > pg_table_size() is only for tables by throwing an error if anything\n> > > other than a table is passed in.\n> > >\n> > > If we decide to preserve the existing behavior of the pg_table_size():\n> > > It seems that for things not backed by the tableAM (indexes and\n> > > sequences), they should still go through calculate_relation_size().\n> > > We can call table_relation_size() based on if relkind is\n> > > RELKIND_RELATION, RELKIND_TOASTVALUE or RELKIND_MATVIEW. Perhaps it\n> > > might be worthwhile making a new macro RELKIND_HAS_TABLE_STORAGE to\n> > > capture these three cases (See RELKIND_HAS_STORAGE). This also ensures\n> > > that we return 0 for things that don't qualify as RELKIND_HAS_STORAGE,\n> > > such as a partitioned table (Currently w/ the patch applied, we return\n> > > NULL for those cases, which is another behavior change)\n> >\n> >\n> > Excellent point. This is the discussion I was longing to have.\n> >\n> > I stand by the decision coded in the patch, that pg_table_size() should\n> > return NULL for other kinds of relations, such as indexes, sequences\n> > etc.\n> >\n> > It is a conscious decision based on the following:\n> >\n> > * Supported by the documentation, pg_table_size() applies to tables only.\n> > For other uses the higher-level functions pg_total_relation_size() or\n> > pg_relation_size() should be used.\n> > * Commit fa352d662e taught pg_relation_size() and friends to return NULL if the object doesn't exist. This makes perfect sense for the\n> > scenarios described in the commit:\n> >\n> > That avoids errors when the functions are used in queries like\n> > \"SELECT pg_relation_size(oid) FROM pg_class\",\n> > and a table is dropped concurrently.\n> >\n> > IMHO: It is more consistent to return NULL when the relation does exist\n> > OR it is not a table kind.\n> > * Returning 0 for things that do not have storage, is nonsensical because\n> > it implies that it can be NON zero at some point. Things that do not\n> > have storage have an unknown size.\n>\n> Fair. We will have to document the behavior change.\n>\n> >\n> > As far as for the argument that users might have trialed and errored\n> > their way into undocumented behaviour, I do not think it is strong\n> > enough to stop us from implementing the documented behaviour.\n>\n> Fair. I would strongly vote for having two additional functions\n> (pg_index_size() and pg_sequence_size()) to strongly signal our intent\n> of banning that kind of use of pg_table_size(). I think it would help\n> users a lot. It is not easy to find what function to call when you want\n> the size of a single index/sequence.\n>\n> > >\n> > > 4.\n> > >\n> > > > @@ -3776,10 +3776,24 @@ listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSys\n> > > > gettext_noop(\"Access Method\"));\n> > > >\n> > > > /*\n> > > >\n> > > >\n> > > > - * As of PostgreSQL 14, do not use pg_table_size() for indexes and\n> > > >\n> > > >\n> > > > - * sequences as it does not behave sanely for those.\n> > > >\n> > > >\n> > > > - *\n> > > > * As of PostgreSQL 9.0, use pg_table_size() to show a more accurate\n> > > > * size of a table, including FSM, VM and TOAST tables.\n> > > > */\n> > > >\n> > > >\n> > > >\n> > > > - if (pset.sversion >= 90000)\n> > > >\n> > > >\n> > > >\n> > > > - if (pset.sversion >= 140000)\n> > > >\n> > > >\n> > > > - appendPQExpBuffer(&buf,\n> > > >\n> > > >\n> > > > - \",\\\\n CASE\"\n> > > >\n> > > >\n> > > > - \" WHEN c.relkind in (\"CppAsString2(RELKIND_INDEX)\", \"\n> > > >\n> > > >\n> > > > - CppAsString2(RELKIND_PARTITIONED_INDEX)\", \"\n> > > >\n> > > >\n> > > > - CppAsString2(RELKIND_SEQUENCE)\") THEN\"\n> > > >\n> > > >\n> > > > - \" pg_catalog.pg_size_pretty(pg_catalog.pg_relation_size(c.oid))\"\n> > > >\n> > > >\n> > > > - \" ELSE\"\n> > > >\n> > > >\n> > > > - \" pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid))\"\n> > > >\n> > > >\n> > > > - \" END as \\\\\"%s\\\\\"\",\n> > > >\n> > > >\n> > > > - gettext_noop(\"Size\"));\n> > > >\n> > > >\n> > > > - else if (pset.sversion >= 90000)\n> > > > appendPQExpBuffer(&buf,\n> > > > \",\\\\n pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid)) as \\\\\"%s\\\\\"\",\n> > > > gettext_noop(\"Size\"));\n> > > >\n> > > >\n> > >\n> > > Following on from point 3, if we decide to preserve the existing behavior,\n> > > we wouldn't need this change, as it would be internalized within\n> > > pg_table_size().\n> >\n> > We really should not decide to preserve the existing behaviour.\n> >\n> > I will reiterate my point: Returning 0 for things that do not have\n> > storage, implies that it can be NON zero at some point. We should not\n> > treat pg_table_size() as an alias for pg_relation_size().\n>\n> +1\n>\n> > >\n> > > 4.\n> > >\n> > > > > - return size;\n> > > > >\n> > > > > - Assert(size < PG_INT64_MAX);\n> > > > >\n> > > > > -\n> > > > > - return (int64)size;\n> > > > > I assume that this change, and the other ones like that, aim to handle int64\n> > > > > overflow? Using the extra legroom of uint64 can still lead to an overflow,\n> > > > > however theoretical it may be. Wouldn't it be better to check for overflow\n> > > > > before adding to size rather than after the fact? Something along the lines of\n> > > > > checking for headroom left:\n> > > > > rel_size = table_relation_size(..);\n> > > > > if (rel_size > (PG_INT64_MAX - total_size))\n> > > > > < error codepath >\n> > > > >\n> > > > >\n> > > > > total_size += rel_size;\n> > > >\n> > > > Actually not, the intention is not to handle overflow. The table_relation_size() returns a uint64 and the calling function returns int64.\n> > > > The Assert() has been placed in order to denote that it is acknowledged that the two functions return different types. I was of the opinion that a run time check will not be needed as even the > smaller type can cover more than 9200 PetaByte tables.\n> > > > If we were to change anything, then I would prefer to change the signature of the pg_*_size family of functions to return uint64 instead.\n> > >\n> > > Changing the signature would be the ideal change for all of this here.\n> > > But Postgres does not have support for an unsigned 64bit integer (bigint\n> > > is signed). One would need to turn to extensions such as [1]. Thus, +1\n> > > to what Daniel said above.\n> >\n> > Apologies, I do not follow. Are you suggesting that we should\n> > introduce overflow tests?\n>\n> Yes, to introduce the same overflow test that Daniel suggested above as\n> returning a uint64 in PG does not really return a uint64 AFAIU (since\n> the pg_**size() functions all return bigint which is signed and there\n> is no uint64 user-facing type).\n\nStatus update for a commitfest entry.\n\nThis patch gets review comments and there was some discussion. It\nseems we're waiting for the patch update. So I've moved this patch to\nthe next commitfest and set it to \"Waiting on Author\".\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Mon, 1 Feb 2021 21:18:52 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": "‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn Monday, February 1, 2021 1:18 PM, Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n\n> On Thu, Nov 12, 2020 at 2:54 AM Soumyadeep Chakraborty\n> soumyadeep2007@gmail.com wrote:\n>\n> > Hey Georgios,\n> > On Tue, Nov 10, 2020 at 6:20 AM gkokolatos@pm.me wrote:\n> >\n> > > ‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\n> > > On Monday, November 9, 2020 7:50 PM, Soumyadeep Chakraborty soumyadeep2007@gmail.com wrote:\n> > >\n> > > > Hey Georgios,\n> > > > Thanks for looking for more avenues to invoke tableAM APIS! Please find\n> > > > my review below:\n> > >\n> > > A great review Soumyadeep, it is much appreciated.\n> > > Please remember to add yourself as a reviewer in the commitfest\n> > > [https://commitfest.postgresql.org/30/2701/]\n> >\n> > Ah yes. Sorry, I forgot that!\n> >\n> > > > On Tue, Oct 13, 2020 at 6:28 AM gkokolatos@pm.me wrote:\n> > > >\n> > > > 1.\n> > > >\n> > > > > /*\n> > > > >\n> > > > > - - heap size, including FSM and VM\n> > > > > - - table size, including FSM and VM\n> > > > > */\n> > > > >\n> > > >\n> > > > We should not mention FSM and VM in dbsize.c at all as these are\n> > > > heap AM specific. We can say:\n> > > > table size, excluding TOAST relation\n> > >\n> > > Yeah, I was thinking that the notion that FSM and VM are still taken\n> > > into account should be stated. We are iterating over ForkNumber\n> > > after all.\n> > > How about phrasing it as:\n> > >\n> > > - table size, including all implemented forks from the AM (e.g. FSM, VM)\n> > > - excluding TOAST relations\n> > >\n> > > Thoughts?\n> >\n> > Yes, I was thinking along the same lines. The concept of a \"fork\" forced\n> > should not be forced down into the tableAM. But that is a discussion for\n> > another day. We can probably say:\n> >\n> > - table size, including all implemented forks from the AM (e.g. FSM, VM\n> > - for the heap AM) excluding TOAST relations\n> >\n> > > > 2.\n> > > >\n> > > > > /*\n> > > > >\n> > > > > - Size of toast relation\n> > > > > */\n> > > > > if (OidIsValid(rel->rd_rel->reltoastrelid))\n> > > > >\n> > > > > - size += calculate_toast_table_size(rel->rd_rel->reltoastrelid);\n> > > > >\n> > > > > - {\n> > > > >\n> > > > > - Relation toastRel;\n> > > > >\n> > > > > -\n> > > > > - toastRel = relation_open(rel->rd_rel->reltoastrelid, AccessShareLock);\n> > > > >\n> > > >\n> > > > We can replace the OidIsValid check with relation_needs_toast_table()\n> > > > and then have the OidIsValid() check in an Assert. Perhaps, that will\n> > > > make things more readable.\n> > >\n> > > Please, allow me to kindly disagree.\n> > > Relation is already open at this stage. Even create_toast_table(), the\n> > > internal workhorse for creating toast relations, does check reltoastrelid\n> > > to test if the relation is already toasted.\n> > > Furthermore, we do call:\n> > >\n> > > - toastRel = relation_open(rel->rd_rel->reltoastrelid, AccessShareLock);\n> > >\n> > > and in order to avoid elog() errors underneath us, we ought to have\n> > > verified the validity of reltoastrelid.\n> > > In short, I think that the code in the proposal is not too unreadable\n> > > nor that it breaks the coding patterns throughout the codebase.\n> > > Am I too wrong?\n> >\n> > No not at all. The code in the proposal is indeed adhering to the\n> > codebase. What I was going for here was to increase the usage of\n> > relation_needs_toast_table(). What I meant was:\n> > if (table_relation_needs_toast_table(rel))\n> > {\n> > if (!OidIsValid(rel->rd_rel->reltoastrelid))\n> > {\n> > elog(ERROR, <errmsg that toast table wasn't found>);\n> > }\n> > //size calculation here..\n> > }\n> > We want to error out if the toast table can't be found and the relation\n> > is expected to have one, which the existing code doesn't handle.\n> >\n> > > > 3.\n> > > >\n> > > > > - if (rel->rd_rel->relkind == RELKIND_RELATION ||\n> > > > > - rel->rd_rel->relkind == RELKIND_TOASTVALUE ||\n> > > > > - rel->rd_rel->relkind == RELKIND_MATVIEW)\n> > > > > - size = calculate_table_size(rel);\n> > > > > - else\n> > > > > - {\n> > > > > - relation_close(rel, AccessShareLock);\n> > > > > - PG_RETURN_NULL();\n> > > > > - }\n> > > >\n> > > > This leads to behavioral changes:\n> > > > I am talking about the case where one calls pg_table_size() on an index.\n> > > > W/o your patch, it returns the size of the index. W/ your patch it\n> > > > returns NULL. Judging by the documentation, this function should not\n> > > > ideally apply to indexes but it does! I have a sinking feeling that lots\n> > > > of users use it for this purpose, as there is no function to calculate\n> > > > the size of a single specific index (except pg_relation_size()).\n> > > > The same argument I have made above applies to sequences. Users may have\n> > > > trial-and-errored their way into finding that pg_table_size() can tell\n> > > > them the size of a specific index/sequence! I don't know how widespread\n> > > > the use is in the user community, so IMO maybe we should be conservative\n> > > > and not introduce this change? Alternatively, we could call out that\n> > > > pg_table_size() is only for tables by throwing an error if anything\n> > > > other than a table is passed in.\n> > > > If we decide to preserve the existing behavior of the pg_table_size():\n> > > > It seems that for things not backed by the tableAM (indexes and\n> > > > sequences), they should still go through calculate_relation_size().\n> > > > We can call table_relation_size() based on if relkind is\n> > > > RELKIND_RELATION, RELKIND_TOASTVALUE or RELKIND_MATVIEW. Perhaps it\n> > > > might be worthwhile making a new macro RELKIND_HAS_TABLE_STORAGE to\n> > > > capture these three cases (See RELKIND_HAS_STORAGE). This also ensures\n> > > > that we return 0 for things that don't qualify as RELKIND_HAS_STORAGE,\n> > > > such as a partitioned table (Currently w/ the patch applied, we return\n> > > > NULL for those cases, which is another behavior change)\n> > >\n> > > Excellent point. This is the discussion I was longing to have.\n> > > I stand by the decision coded in the patch, that pg_table_size() should\n> > > return NULL for other kinds of relations, such as indexes, sequences\n> > > etc.\n> > > It is a conscious decision based on the following:\n> > >\n> > > - Supported by the documentation, pg_table_size() applies to tables only.\n> > > For other uses the higher-level functions pg_total_relation_size() or\n> > > pg_relation_size() should be used.\n> > >\n> > > - Commit fa352d662e taught pg_relation_size() and friends to return NULL if the object doesn't exist. This makes perfect sense for the\n> > > scenarios described in the commit:\n> > > That avoids errors when the functions are used in queries like\n> > > \"SELECT pg_relation_size(oid) FROM pg_class\",\n> > > and a table is dropped concurrently.\n> > >\n> > >\n> > > IMHO: It is more consistent to return NULL when the relation does exist\n> > > OR it is not a table kind.\n> > >\n> > > - Returning 0 for things that do not have storage, is nonsensical because\n> > > it implies that it can be NON zero at some point. Things that do not\n> > > have storage have an unknown size.\n> > >\n> >\n> > Fair. We will have to document the behavior change.\n> >\n> > > As far as for the argument that users might have trialed and errored\n> > > their way into undocumented behaviour, I do not think it is strong\n> > > enough to stop us from implementing the documented behaviour.\n> >\n> > Fair. I would strongly vote for having two additional functions\n> > (pg_index_size() and pg_sequence_size()) to strongly signal our intent\n> > of banning that kind of use of pg_table_size(). I think it would help\n> > users a lot. It is not easy to find what function to call when you want\n> > the size of a single index/sequence.\n> >\n> > > > 4.\n> > > >\n> > > > > @@ -3776,10 +3776,24 @@ listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSys\n> > > > > gettext_noop(\"Access Method\"));\n> > > > >\n> > > > > /*\n> > > > >\n> > > > >\n> > > > > - * As of PostgreSQL 14, do not use pg_table_size() for indexes and\n> > > > >\n> > > > >\n> > > > > - * sequences as it does not behave sanely for those.\n> > > > >\n> > > > >\n> > > > > - *\n> > > > > * As of PostgreSQL 9.0, use pg_table_size() to show a more accurate\n> > > > > * size of a table, including FSM, VM and TOAST tables.\n> > > > > */\n> > > > >\n> > > > >\n> > > > > - if (pset.sversion >= 90000)\n> > > > >\n> > > > >\n> > > > > - if (pset.sversion >= 140000)\n> > > > >\n> > > > >\n> > > > > - appendPQExpBuffer(&buf,\n> > > > >\n> > > > >\n> > > > > - \",\\\\\\\\n CASE\"\n> > > > >\n> > > > >\n> > > > > - \" WHEN c.relkind in (\"CppAsString2(RELKIND_INDEX)\", \"\n> > > > >\n> > > > >\n> > > > > - CppAsString2(RELKIND_PARTITIONED_INDEX)\", \"\n> > > > >\n> > > > >\n> > > > > - CppAsString2(RELKIND_SEQUENCE)\") THEN\"\n> > > > >\n> > > > >\n> > > > > - \" pg_catalog.pg_size_pretty(pg_catalog.pg_relation_size(c.oid))\"\n> > > > >\n> > > > >\n> > > > > - \" ELSE\"\n> > > > >\n> > > > >\n> > > > > - \" pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid))\"\n> > > > >\n> > > > >\n> > > > > - \" END as \\\\\\\\\"%s\\\\\\\\\"\",\n> > > > >\n> > > > >\n> > > > > - gettext_noop(\"Size\"));\n> > > > >\n> > > > >\n> > > > > - else if (pset.sversion >= 90000)\n> > > > > appendPQExpBuffer(&buf,\n> > > > > \",\\\\\\\\n pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid)) as \\\\\\\\\"%s\\\\\\\\\"\",\n> > > > > gettext_noop(\"Size\"));\n> > > > >\n> > > > >\n> > > >\n> > > > Following on from point 3, if we decide to preserve the existing behavior,\n> > > > we wouldn't need this change, as it would be internalized within\n> > > > pg_table_size().\n> > >\n> > > We really should not decide to preserve the existing behaviour.\n> > > I will reiterate my point: Returning 0 for things that do not have\n> > > storage, implies that it can be NON zero at some point. We should not\n> > > treat pg_table_size() as an alias for pg_relation_size().\n> >\n> > +1\n> >\n> > > > 4.\n> > > >\n> > > > > > - return size;\n> > > > > >\n> > > > > > - Assert(size < PG_INT64_MAX);\n> > > > > >\n> > > > > > -\n> > > > > > - return (int64)size;\n> > > > > > I assume that this change, and the other ones like that, aim to handle int64\n> > > > > > overflow? Using the extra legroom of uint64 can still lead to an overflow,\n> > > > > > however theoretical it may be. Wouldn't it be better to check for overflow\n> > > > > > before adding to size rather than after the fact? Something along the lines of\n> > > > > > checking for headroom left:\n> > > > > > rel_size = table_relation_size(..);\n> > > > > > if (rel_size > (PG_INT64_MAX - total_size))\n> > > > > > < error codepath >\n> > > > > >\n> > > > > >\n> > > > > > total_size += rel_size;\n> > > > >\n> > > > > Actually not, the intention is not to handle overflow. The table_relation_size() returns a uint64 and the calling function returns int64.\n> > > > > The Assert() has been placed in order to denote that it is acknowledged that the two functions return different types. I was of the opinion that a run time check will not be needed as even the > smaller type can cover more than 9200 PetaByte tables.\n> > > > > If we were to change anything, then I would prefer to change the signature of the pg_*_size family of functions to return uint64 instead.\n> > > >\n> > > > Changing the signature would be the ideal change for all of this here.\n> > > > But Postgres does not have support for an unsigned 64bit integer (bigint\n> > > > is signed). One would need to turn to extensions such as [1]. Thus, +1\n> > > > to what Daniel said above.\n> > >\n> > > Apologies, I do not follow. Are you suggesting that we should\n> > > introduce overflow tests?\n> >\n> > Yes, to introduce the same overflow test that Daniel suggested above as\n> > returning a uint64 in PG does not really return a uint64 AFAIU (since\n> > the pg_**size() functions all return bigint which is signed and there\n> > is no uint64 user-facing type).\n>\n> Status update for a commitfest entry.\n>\n> This patch gets review comments and there was some discussion. It\n> seems we're waiting for the patch update. So I've moved this patch to\n> the next commitfest and set it to \"Waiting on Author\".\n\nThank you for your patience.\n\nPlease find v3 attached. I will reset the status to 'Ready for review'.\n\n>\n> Regards,\n>\n> --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n>\n> Masahiko Sawada\n> EDB: https://www.enterprisedb.com/", "msg_date": "Fri, 19 Feb 2021 15:57:22 +0000", "msg_from": "gkokolatos@pm.me", "msg_from_op": true, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": "\n\n\n\n\n‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn Friday, February 19, 2021 4:57 PM, <gkokolatos@pm.me> wrote:\n\n>\n>\n> ‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\n> On Monday, February 1, 2021 1:18 PM, Masahiko Sawada sawada.mshk@gmail.com wrote:\n>\n> > On Thu, Nov 12, 2020 at 2:54 AM Soumyadeep Chakraborty\n> > soumyadeep2007@gmail.com wrote:\n> >\n> > > Hey Georgios,\n> > > On Tue, Nov 10, 2020 at 6:20 AM gkokolatos@pm.me wrote:\n> > >\n> > > > ‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\n> > > > On Monday, November 9, 2020 7:50 PM, Soumyadeep Chakraborty soumyadeep2007@gmail.com wrote:\n> > > >\n> > > > > Hey Georgios,\n> > > > > Thanks for looking for more avenues to invoke tableAM APIS! Please find\n> > > > > my review below:\n> > > >\n> > > > A great review Soumyadeep, it is much appreciated.\n> > > > Please remember to add yourself as a reviewer in the commitfest\n> > > > [https://commitfest.postgresql.org/30/2701/]\n> > >\n> > > Ah yes. Sorry, I forgot that!\n> > >\n> > > > > On Tue, Oct 13, 2020 at 6:28 AM gkokolatos@pm.me wrote:\n> > > > >\n> > > > > 1.\n> > > > >\n> > > > > > /*\n> > > > > >\n> > > > > > - - heap size, including FSM and VM\n> > > > > > - - table size, including FSM and VM\n> > > > > > */\n> > > > > >\n> > > > >\n> > > > > We should not mention FSM and VM in dbsize.c at all as these are\n> > > > > heap AM specific. We can say:\n> > > > > table size, excluding TOAST relation\n> > > >\n> > > > Yeah, I was thinking that the notion that FSM and VM are still taken\n> > > > into account should be stated. We are iterating over ForkNumber\n> > > > after all.\n> > > > How about phrasing it as:\n> > > >\n> > > > - table size, including all implemented forks from the AM (e.g. FSM, VM)\n> > > > - excluding TOAST relations\n> > > >\n> > > > Thoughts?\n> > >\n> > > Yes, I was thinking along the same lines. The concept of a \"fork\" forced\n> > > should not be forced down into the tableAM. But that is a discussion for\n> > > another day. We can probably say:\n> > >\n> > > - table size, including all implemented forks from the AM (e.g. FSM, VM\n> > > - for the heap AM) excluding TOAST relations\n> > >\n> > > > > 2.\n> > > > >\n> > > > > > /*\n> > > > > >\n> > > > > > - Size of toast relation\n> > > > > > */\n> > > > > > if (OidIsValid(rel->rd_rel->reltoastrelid))\n> > > > > >\n> > > > > > - size += calculate_toast_table_size(rel->rd_rel->reltoastrelid);\n> > > > > >\n> > > > > > - {\n> > > > > >\n> > > > > > - Relation toastRel;\n> > > > > >\n> > > > > > -\n> > > > > > - toastRel = relation_open(rel->rd_rel->reltoastrelid, AccessShareLock);\n> > > > > >\n> > > > >\n> > > > > We can replace the OidIsValid check with relation_needs_toast_table()\n> > > > > and then have the OidIsValid() check in an Assert. Perhaps, that will\n> > > > > make things more readable.\n> > > >\n> > > > Please, allow me to kindly disagree.\n> > > > Relation is already open at this stage. Even create_toast_table(), the\n> > > > internal workhorse for creating toast relations, does check reltoastrelid\n> > > > to test if the relation is already toasted.\n> > > > Furthermore, we do call:\n> > > >\n> > > > - toastRel = relation_open(rel->rd_rel->reltoastrelid, AccessShareLock);\n> > > >\n> > > > and in order to avoid elog() errors underneath us, we ought to have\n> > > > verified the validity of reltoastrelid.\n> > > > In short, I think that the code in the proposal is not too unreadable\n> > > > nor that it breaks the coding patterns throughout the codebase.\n> > > > Am I too wrong?\n> > >\n> > > No not at all. The code in the proposal is indeed adhering to the\n> > > codebase. What I was going for here was to increase the usage of\n> > > relation_needs_toast_table(). What I meant was:\n> > > if (table_relation_needs_toast_table(rel))\n> > > {\n> > > if (!OidIsValid(rel->rd_rel->reltoastrelid))\n> > > {\n> > > elog(ERROR, <errmsg that toast table wasn't found>);\n> > > }\n> > > //size calculation here..\n> > > }\n> > > We want to error out if the toast table can't be found and the relation\n> > > is expected to have one, which the existing code doesn't handle.\n> > >\n> > > > > 3.\n> > > > >\n> > > > > > - if (rel->rd_rel->relkind == RELKIND_RELATION ||\n> > > > > > - rel->rd_rel->relkind == RELKIND_TOASTVALUE ||\n> > > > > > - rel->rd_rel->relkind == RELKIND_MATVIEW)\n> > > > > > - size = calculate_table_size(rel);\n> > > > > > - else\n> > > > > > - {\n> > > > > > - relation_close(rel, AccessShareLock);\n> > > > > > - PG_RETURN_NULL();\n> > > > > > - }\n> > > > >\n> > > > > This leads to behavioral changes:\n> > > > > I am talking about the case where one calls pg_table_size() on an index.\n> > > > > W/o your patch, it returns the size of the index. W/ your patch it\n> > > > > returns NULL. Judging by the documentation, this function should not\n> > > > > ideally apply to indexes but it does! I have a sinking feeling that lots\n> > > > > of users use it for this purpose, as there is no function to calculate\n> > > > > the size of a single specific index (except pg_relation_size()).\n> > > > > The same argument I have made above applies to sequences. Users may have\n> > > > > trial-and-errored their way into finding that pg_table_size() can tell\n> > > > > them the size of a specific index/sequence! I don't know how widespread\n> > > > > the use is in the user community, so IMO maybe we should be conservative\n> > > > > and not introduce this change? Alternatively, we could call out that\n> > > > > pg_table_size() is only for tables by throwing an error if anything\n> > > > > other than a table is passed in.\n> > > > > If we decide to preserve the existing behavior of the pg_table_size():\n> > > > > It seems that for things not backed by the tableAM (indexes and\n> > > > > sequences), they should still go through calculate_relation_size().\n> > > > > We can call table_relation_size() based on if relkind is\n> > > > > RELKIND_RELATION, RELKIND_TOASTVALUE or RELKIND_MATVIEW. Perhaps it\n> > > > > might be worthwhile making a new macro RELKIND_HAS_TABLE_STORAGE to\n> > > > > capture these three cases (See RELKIND_HAS_STORAGE). This also ensures\n> > > > > that we return 0 for things that don't qualify as RELKIND_HAS_STORAGE,\n> > > > > such as a partitioned table (Currently w/ the patch applied, we return\n> > > > > NULL for those cases, which is another behavior change)\n> > > >\n> > > > Excellent point. This is the discussion I was longing to have.\n> > > > I stand by the decision coded in the patch, that pg_table_size() should\n> > > > return NULL for other kinds of relations, such as indexes, sequences\n> > > > etc.\n> > > > It is a conscious decision based on the following:\n> > > >\n> > > > - Supported by the documentation, pg_table_size() applies to tables only.\n> > > > For other uses the higher-level functions pg_total_relation_size() or\n> > > > pg_relation_size() should be used.\n> > > >\n> > > > - Commit fa352d662e taught pg_relation_size() and friends to return NULL if the object doesn't exist. This makes perfect sense for the\n> > > > scenarios described in the commit:\n> > > > That avoids errors when the functions are used in queries like\n> > > > \"SELECT pg_relation_size(oid) FROM pg_class\",\n> > > > and a table is dropped concurrently.\n> > > >\n> > > >\n> > > > IMHO: It is more consistent to return NULL when the relation does exist\n> > > > OR it is not a table kind.\n> > > >\n> > > > - Returning 0 for things that do not have storage, is nonsensical because\n> > > > it implies that it can be NON zero at some point. Things that do not\n> > > > have storage have an unknown size.\n> > > >\n> > >\n> > > Fair. We will have to document the behavior change.\n> > >\n> > > > As far as for the argument that users might have trialed and errored\n> > > > their way into undocumented behaviour, I do not think it is strong\n> > > > enough to stop us from implementing the documented behaviour.\n> > >\n> > > Fair. I would strongly vote for having two additional functions\n> > > (pg_index_size() and pg_sequence_size()) to strongly signal our intent\n> > > of banning that kind of use of pg_table_size(). I think it would help\n> > > users a lot. It is not easy to find what function to call when you want\n> > > the size of a single index/sequence.\n> > >\n> > > > > 4.\n> > > > >\n> > > > > > @@ -3776,10 +3776,24 @@ listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSys\n> > > > > > gettext_noop(\"Access Method\"));\n> > > > > >\n> > > > > > /*\n> > > > > >\n> > > > > >\n> > > > > > - * As of PostgreSQL 14, do not use pg_table_size() for indexes and\n> > > > > >\n> > > > > >\n> > > > > > - * sequences as it does not behave sanely for those.\n> > > > > >\n> > > > > >\n> > > > > > - *\n> > > > > > * As of PostgreSQL 9.0, use pg_table_size() to show a more accurate\n> > > > > > * size of a table, including FSM, VM and TOAST tables.\n> > > > > > */\n> > > > > >\n> > > > > >\n> > > > > > - if (pset.sversion >= 90000)\n> > > > > >\n> > > > > >\n> > > > > > - if (pset.sversion >= 140000)\n> > > > > >\n> > > > > >\n> > > > > > - appendPQExpBuffer(&buf,\n> > > > > >\n> > > > > >\n> > > > > > - \",\\\\\\\\\\\\\\\\n CASE\"\n> > > > > >\n> > > > > >\n> > > > > > - \" WHEN c.relkind in (\"CppAsString2(RELKIND_INDEX)\", \"\n> > > > > >\n> > > > > >\n> > > > > > - CppAsString2(RELKIND_PARTITIONED_INDEX)\", \"\n> > > > > >\n> > > > > >\n> > > > > > - CppAsString2(RELKIND_SEQUENCE)\") THEN\"\n> > > > > >\n> > > > > >\n> > > > > > - \" pg_catalog.pg_size_pretty(pg_catalog.pg_relation_size(c.oid))\"\n> > > > > >\n> > > > > >\n> > > > > > - \" ELSE\"\n> > > > > >\n> > > > > >\n> > > > > > - \" pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid))\"\n> > > > > >\n> > > > > >\n> > > > > > - \" END as \\\\\\\\\\\\\\\\\"%s\\\\\\\\\\\\\\\\\"\",\n> > > > > >\n> > > > > >\n> > > > > > - gettext_noop(\"Size\"));\n> > > > > >\n> > > > > >\n> > > > > > - else if (pset.sversion >= 90000)\n> > > > > > appendPQExpBuffer(&buf,\n> > > > > > \",\\\\\\\\\\\\\\\\n pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid)) as \\\\\\\\\\\\\\\\\"%s\\\\\\\\\\\\\\\\\"\",\n> > > > > > gettext_noop(\"Size\"));\n> > > > > >\n> > > > > >\n> > > > >\n> > > > > Following on from point 3, if we decide to preserve the existing behavior,\n> > > > > we wouldn't need this change, as it would be internalized within\n> > > > > pg_table_size().\n> > > >\n> > > > We really should not decide to preserve the existing behaviour.\n> > > > I will reiterate my point: Returning 0 for things that do not have\n> > > > storage, implies that it can be NON zero at some point. We should not\n> > > > treat pg_table_size() as an alias for pg_relation_size().\n> > >\n> > > +1\n> > >\n> > > > > 4.\n> > > > >\n> > > > > > > - return size;\n> > > > > > >\n> > > > > > > - Assert(size < PG_INT64_MAX);\n> > > > > > >\n> > > > > > > -\n> > > > > > > - return (int64)size;\n> > > > > > > I assume that this change, and the other ones like that, aim to handle int64\n> > > > > > > overflow? Using the extra legroom of uint64 can still lead to an overflow,\n> > > > > > > however theoretical it may be. Wouldn't it be better to check for overflow\n> > > > > > > before adding to size rather than after the fact? Something along the lines of\n> > > > > > > checking for headroom left:\n> > > > > > > rel_size = table_relation_size(..);\n> > > > > > > if (rel_size > (PG_INT64_MAX - total_size))\n> > > > > > > < error codepath >\n> > > > > > >\n> > > > > > >\n> > > > > > > total_size += rel_size;\n> > > > > >\n> > > > > > Actually not, the intention is not to handle overflow. The table_relation_size() returns a uint64 and the calling function returns int64.\n> > > > > > The Assert() has been placed in order to denote that it is acknowledged that the two functions return different types. I was of the opinion that a run time check will not be needed as even the > smaller type can cover more than 9200 PetaByte tables.\n> > > > > > If we were to change anything, then I would prefer to change the signature of the pg_*_size family of functions to return uint64 instead.\n> > > > >\n> > > > > Changing the signature would be the ideal change for all of this here.\n> > > > > But Postgres does not have support for an unsigned 64bit integer (bigint\n> > > > > is signed). One would need to turn to extensions such as [1]. Thus, +1\n> > > > > to what Daniel said above.\n> > > >\n> > > > Apologies, I do not follow. Are you suggesting that we should\n> > > > introduce overflow tests?\n> > >\n> > > Yes, to introduce the same overflow test that Daniel suggested above as\n> > > returning a uint64 in PG does not really return a uint64 AFAIU (since\n> > > the pg_**size() functions all return bigint which is signed and there\n> > > is no uint64 user-facing type).\n> >\n> > Status update for a commitfest entry.\n> > This patch gets review comments and there was some discussion. It\n> > seems we're waiting for the patch update. So I've moved this patch to\n> > the next commitfest and set it to \"Waiting on Author\".\n>\n> Thank you for your patience.\n>\n> Please find v3 attached. I will reset the status to 'Ready for review'.\n\n\nVersion 3 of the patch broke the cfbot. Please find v4 attached.\n\nThis patch requires a catalog version bump.\n\nCheers,\n//Georgios -- https://www.vmware.com\n\n\n>\n> > Regards,\n> >\n> > Masahiko Sawada\n> > EDB: https://www.enterprisedb.com/\n\n\n\n\n", "msg_date": "Wed, 24 Feb 2021 14:34:25 +0000", "msg_from": "gkokolatos@pm.me", "msg_from_op": true, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": "‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn Wednesday, February 24, 2021 3:34 PM, <gkokolatos@pm.me> wrote:\n\n>\n>\n> ‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\n> On Friday, February 19, 2021 4:57 PM, gkokolatos@pm.me wrote:\n>\n> > ‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\n> > On Monday, February 1, 2021 1:18 PM, Masahiko Sawada sawada.mshk@gmail.com wrote:\n> >\n> > > On Thu, Nov 12, 2020 at 2:54 AM Soumyadeep Chakraborty\n> > > soumyadeep2007@gmail.com wrote:\n> > >\n> > > > Hey Georgios,\n> > > > On Tue, Nov 10, 2020 at 6:20 AM gkokolatos@pm.me wrote:\n> > > >\n> > > > > ‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\n> > > > > On Monday, November 9, 2020 7:50 PM, Soumyadeep Chakraborty soumyadeep2007@gmail.com wrote:\n> > > > >\n> > > > > > Hey Georgios,\n> > > > > > Thanks for looking for more avenues to invoke tableAM APIS! Please find\n> > > > > > my review below:\n> > > > >\n> > > > > A great review Soumyadeep, it is much appreciated.\n> > > > > Please remember to add yourself as a reviewer in the commitfest\n> > > > > [https://commitfest.postgresql.org/30/2701/]\n> > > >\n> > > > Ah yes. Sorry, I forgot that!\n> > > >\n> > > > > > On Tue, Oct 13, 2020 at 6:28 AM gkokolatos@pm.me wrote:\n> > > > > >\n> > > > > > 1.\n> > > > > >\n> > > > > > > /*\n> > > > > > >\n> > > > > > > - - heap size, including FSM and VM\n> > > > > > > - - table size, including FSM and VM\n> > > > > > > */\n> > > > > > >\n> > > > > >\n> > > > > > We should not mention FSM and VM in dbsize.c at all as these are\n> > > > > > heap AM specific. We can say:\n> > > > > > table size, excluding TOAST relation\n> > > > >\n> > > > > Yeah, I was thinking that the notion that FSM and VM are still taken\n> > > > > into account should be stated. We are iterating over ForkNumber\n> > > > > after all.\n> > > > > How about phrasing it as:\n> > > > >\n> > > > > - table size, including all implemented forks from the AM (e.g. FSM, VM)\n> > > > > - excluding TOAST relations\n> > > > >\n> > > > > Thoughts?\n> > > >\n> > > > Yes, I was thinking along the same lines. The concept of a \"fork\" forced\n> > > > should not be forced down into the tableAM. But that is a discussion for\n> > > > another day. We can probably say:\n> > > >\n> > > > - table size, including all implemented forks from the AM (e.g. FSM, VM\n> > > > - for the heap AM) excluding TOAST relations\n> > > >\n> > > > > > 2.\n> > > > > >\n> > > > > > > /*\n> > > > > > >\n> > > > > > > - Size of toast relation\n> > > > > > > */\n> > > > > > > if (OidIsValid(rel->rd_rel->reltoastrelid))\n> > > > > > >\n> > > > > > > - size += calculate_toast_table_size(rel->rd_rel->reltoastrelid);\n> > > > > > >\n> > > > > > > - {\n> > > > > > >\n> > > > > > > - Relation toastRel;\n> > > > > > >\n> > > > > > > -\n> > > > > > > - toastRel = relation_open(rel->rd_rel->reltoastrelid, AccessShareLock);\n> > > > > > >\n> > > > > >\n> > > > > > We can replace the OidIsValid check with relation_needs_toast_table()\n> > > > > > and then have the OidIsValid() check in an Assert. Perhaps, that will\n> > > > > > make things more readable.\n> > > > >\n> > > > > Please, allow me to kindly disagree.\n> > > > > Relation is already open at this stage. Even create_toast_table(), the\n> > > > > internal workhorse for creating toast relations, does check reltoastrelid\n> > > > > to test if the relation is already toasted.\n> > > > > Furthermore, we do call:\n> > > > >\n> > > > > - toastRel = relation_open(rel->rd_rel->reltoastrelid, AccessShareLock);\n> > > > >\n> > > > > and in order to avoid elog() errors underneath us, we ought to have\n> > > > > verified the validity of reltoastrelid.\n> > > > > In short, I think that the code in the proposal is not too unreadable\n> > > > > nor that it breaks the coding patterns throughout the codebase.\n> > > > > Am I too wrong?\n> > > >\n> > > > No not at all. The code in the proposal is indeed adhering to the\n> > > > codebase. What I was going for here was to increase the usage of\n> > > > relation_needs_toast_table(). What I meant was:\n> > > > if (table_relation_needs_toast_table(rel))\n> > > > {\n> > > > if (!OidIsValid(rel->rd_rel->reltoastrelid))\n> > > > {\n> > > > elog(ERROR, <errmsg that toast table wasn't found>);\n> > > > }\n> > > > //size calculation here..\n> > > > }\n> > > > We want to error out if the toast table can't be found and the relation\n> > > > is expected to have one, which the existing code doesn't handle.\n> > > >\n> > > > > > 3.\n> > > > > >\n> > > > > > > - if (rel->rd_rel->relkind == RELKIND_RELATION ||\n> > > > > > > - rel->rd_rel->relkind == RELKIND_TOASTVALUE ||\n> > > > > > > - rel->rd_rel->relkind == RELKIND_MATVIEW)\n> > > > > > > - size = calculate_table_size(rel);\n> > > > > > > - else\n> > > > > > > - {\n> > > > > > > - relation_close(rel, AccessShareLock);\n> > > > > > > - PG_RETURN_NULL();\n> > > > > > > - }\n> > > > > >\n> > > > > > This leads to behavioral changes:\n> > > > > > I am talking about the case where one calls pg_table_size() on an index.\n> > > > > > W/o your patch, it returns the size of the index. W/ your patch it\n> > > > > > returns NULL. Judging by the documentation, this function should not\n> > > > > > ideally apply to indexes but it does! I have a sinking feeling that lots\n> > > > > > of users use it for this purpose, as there is no function to calculate\n> > > > > > the size of a single specific index (except pg_relation_size()).\n> > > > > > The same argument I have made above applies to sequences. Users may have\n> > > > > > trial-and-errored their way into finding that pg_table_size() can tell\n> > > > > > them the size of a specific index/sequence! I don't know how widespread\n> > > > > > the use is in the user community, so IMO maybe we should be conservative\n> > > > > > and not introduce this change? Alternatively, we could call out that\n> > > > > > pg_table_size() is only for tables by throwing an error if anything\n> > > > > > other than a table is passed in.\n> > > > > > If we decide to preserve the existing behavior of the pg_table_size():\n> > > > > > It seems that for things not backed by the tableAM (indexes and\n> > > > > > sequences), they should still go through calculate_relation_size().\n> > > > > > We can call table_relation_size() based on if relkind is\n> > > > > > RELKIND_RELATION, RELKIND_TOASTVALUE or RELKIND_MATVIEW. Perhaps it\n> > > > > > might be worthwhile making a new macro RELKIND_HAS_TABLE_STORAGE to\n> > > > > > capture these three cases (See RELKIND_HAS_STORAGE). This also ensures\n> > > > > > that we return 0 for things that don't qualify as RELKIND_HAS_STORAGE,\n> > > > > > such as a partitioned table (Currently w/ the patch applied, we return\n> > > > > > NULL for those cases, which is another behavior change)\n> > > > >\n> > > > > Excellent point. This is the discussion I was longing to have.\n> > > > > I stand by the decision coded in the patch, that pg_table_size() should\n> > > > > return NULL for other kinds of relations, such as indexes, sequences\n> > > > > etc.\n> > > > > It is a conscious decision based on the following:\n> > > > >\n> > > > > - Supported by the documentation, pg_table_size() applies to tables only.\n> > > > > For other uses the higher-level functions pg_total_relation_size() or\n> > > > > pg_relation_size() should be used.\n> > > > >\n> > > > > - Commit fa352d662e taught pg_relation_size() and friends to return NULL if the object doesn't exist. This makes perfect sense for the\n> > > > > scenarios described in the commit:\n> > > > > That avoids errors when the functions are used in queries like\n> > > > > \"SELECT pg_relation_size(oid) FROM pg_class\",\n> > > > > and a table is dropped concurrently.\n> > > > >\n> > > > >\n> > > > > IMHO: It is more consistent to return NULL when the relation does exist\n> > > > > OR it is not a table kind.\n> > > > >\n> > > > > - Returning 0 for things that do not have storage, is nonsensical because\n> > > > > it implies that it can be NON zero at some point. Things that do not\n> > > > > have storage have an unknown size.\n> > > > >\n> > > >\n> > > > Fair. We will have to document the behavior change.\n> > > >\n> > > > > As far as for the argument that users might have trialed and errored\n> > > > > their way into undocumented behaviour, I do not think it is strong\n> > > > > enough to stop us from implementing the documented behaviour.\n> > > >\n> > > > Fair. I would strongly vote for having two additional functions\n> > > > (pg_index_size() and pg_sequence_size()) to strongly signal our intent\n> > > > of banning that kind of use of pg_table_size(). I think it would help\n> > > > users a lot. It is not easy to find what function to call when you want\n> > > > the size of a single index/sequence.\n> > > >\n> > > > > > 4.\n> > > > > >\n> > > > > > > @@ -3776,10 +3776,24 @@ listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSys\n> > > > > > > gettext_noop(\"Access Method\"));\n> > > > > > >\n> > > > > > > /*\n> > > > > > >\n> > > > > > >\n> > > > > > > - * As of PostgreSQL 14, do not use pg_table_size() for indexes and\n> > > > > > >\n> > > > > > >\n> > > > > > > - * sequences as it does not behave sanely for those.\n> > > > > > >\n> > > > > > >\n> > > > > > > - *\n> > > > > > > * As of PostgreSQL 9.0, use pg_table_size() to show a more accurate\n> > > > > > > * size of a table, including FSM, VM and TOAST tables.\n> > > > > > > */\n> > > > > > >\n> > > > > > >\n> > > > > > > - if (pset.sversion >= 90000)\n> > > > > > >\n> > > > > > >\n> > > > > > > - if (pset.sversion >= 140000)\n> > > > > > >\n> > > > > > >\n> > > > > > > - appendPQExpBuffer(&buf,\n> > > > > > >\n> > > > > > >\n> > > > > > > - \",\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n CASE\"\n> > > > > > >\n> > > > > > >\n> > > > > > > - \" WHEN c.relkind in (\"CppAsString2(RELKIND_INDEX)\", \"\n> > > > > > >\n> > > > > > >\n> > > > > > > - CppAsString2(RELKIND_PARTITIONED_INDEX)\", \"\n> > > > > > >\n> > > > > > >\n> > > > > > > - CppAsString2(RELKIND_SEQUENCE)\") THEN\"\n> > > > > > >\n> > > > > > >\n> > > > > > > - \" pg_catalog.pg_size_pretty(pg_catalog.pg_relation_size(c.oid))\"\n> > > > > > >\n> > > > > > >\n> > > > > > > - \" ELSE\"\n> > > > > > >\n> > > > > > >\n> > > > > > > - \" pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid))\"\n> > > > > > >\n> > > > > > >\n> > > > > > > - \" END as \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"%s\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\",\n> > > > > > >\n> > > > > > >\n> > > > > > > - gettext_noop(\"Size\"));\n> > > > > > >\n> > > > > > >\n> > > > > > > - else if (pset.sversion >= 90000)\n> > > > > > > appendPQExpBuffer(&buf,\n> > > > > > > \",\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid)) as \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"%s\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\",\n> > > > > > > gettext_noop(\"Size\"));\n> > > > > > >\n> > > > > > >\n> > > > > >\n> > > > > > Following on from point 3, if we decide to preserve the existing behavior,\n> > > > > > we wouldn't need this change, as it would be internalized within\n> > > > > > pg_table_size().\n> > > > >\n> > > > > We really should not decide to preserve the existing behaviour.\n> > > > > I will reiterate my point: Returning 0 for things that do not have\n> > > > > storage, implies that it can be NON zero at some point. We should not\n> > > > > treat pg_table_size() as an alias for pg_relation_size().\n> > > >\n> > > > +1\n> > > >\n> > > > > > 4.\n> > > > > >\n> > > > > > > > - return size;\n> > > > > > > >\n> > > > > > > > - Assert(size < PG_INT64_MAX);\n> > > > > > > >\n> > > > > > > > -\n> > > > > > > > - return (int64)size;\n> > > > > > > > I assume that this change, and the other ones like that, aim to handle int64\n> > > > > > > > overflow? Using the extra legroom of uint64 can still lead to an overflow,\n> > > > > > > > however theoretical it may be. Wouldn't it be better to check for overflow\n> > > > > > > > before adding to size rather than after the fact? Something along the lines of\n> > > > > > > > checking for headroom left:\n> > > > > > > > rel_size = table_relation_size(..);\n> > > > > > > > if (rel_size > (PG_INT64_MAX - total_size))\n> > > > > > > > < error codepath >\n> > > > > > > >\n> > > > > > > >\n> > > > > > > > total_size += rel_size;\n> > > > > > >\n> > > > > > > Actually not, the intention is not to handle overflow. The table_relation_size() returns a uint64 and the calling function returns int64.\n> > > > > > > The Assert() has been placed in order to denote that it is acknowledged that the two functions return different types. I was of the opinion that a run time check will not be needed as even the > smaller type can cover more than 9200 PetaByte tables.\n> > > > > > > If we were to change anything, then I would prefer to change the signature of the pg_*_size family of functions to return uint64 instead.\n> > > > > >\n> > > > > > Changing the signature would be the ideal change for all of this here.\n> > > > > > But Postgres does not have support for an unsigned 64bit integer (bigint\n> > > > > > is signed). One would need to turn to extensions such as [1]. Thus, +1\n> > > > > > to what Daniel said above.\n> > > > >\n> > > > > Apologies, I do not follow. Are you suggesting that we should\n> > > > > introduce overflow tests?\n> > > >\n> > > > Yes, to introduce the same overflow test that Daniel suggested above as\n> > > > returning a uint64 in PG does not really return a uint64 AFAIU (since\n> > > > the pg_**size() functions all return bigint which is signed and there\n> > > > is no uint64 user-facing type).\n> > >\n> > > Status update for a commitfest entry.\n> > > This patch gets review comments and there was some discussion. It\n> > > seems we're waiting for the patch update. So I've moved this patch to\n> > > the next commitfest and set it to \"Waiting on Author\".\n> >\n> > Thank you for your patience.\n> > Please find v3 attached. I will reset the status to 'Ready for review'.\n>\n> Version 3 of the patch broke the cfbot. Please find v4 attached.\n>\n> This patch requires a catalog version bump.\n\nNow with attachment. Apologies for the chatter.\n\n>\n> Cheers,\n> //Georgios -- https://www.vmware.com\n>\n> > > Regards,\n> > > Masahiko Sawada\n> > > EDB: https://www.enterprisedb.com/", "msg_date": "Wed, 24 Feb 2021 14:35:51 +0000", "msg_from": "gkokolatos@pm.me", "msg_from_op": true, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": "On Wed, Feb 24, 2021 at 02:35:51PM +0000, gkokolatos@pm.me wrote:\n> Now with attachment. Apologies for the chatter.\n\nThe patch has no documentation for the two new functions, so it is a\nbit hard to understand what is the value brought here, and what is the\ngoal wanted just by reading the patch, except that this switches the\nsize reported for views to NULL instead of zero bytes by reading the\nregression tests.\n\nPlease note that reporting zero is not wrong for views IMO as these\nhave no physical storage, so, while it is possible to argue that a\nsize of zero could imply that this relation size could not be zero, it\nwill never change, so I'd rather let this behavior as it is. I\nwould bet, additionally, that this could break existing use cases.\nReporting NULL, on the contrary, as your patch does, makes things\nworse in some ways because that's what pg_relation_size would report\nwhen a relation does not exist anymore. Imagine for example the case\nof a DROP TABLE run in parallel of a scan of pg_class using\npg_relation_size(). So it becomes impossible to know if a relation\nhas been removed or not. This joins some points raised by Soumyadeep\nupthread.\n\nAnyway, as mentioned by other people upthread, I am not really\nconvinced either that we should have more flavors of size functions,\nparticularly depending on the relkind as this would be confusing for\nthe end-user. pg_relation_size() can already do this job for all\nrelkinds that use segment files, so it should still be able to hold\nits ground and maintain a consistent behavior with what it does\ncurrently.\n\n+static int64\n+calculate_table_fork_size(Relation rel, ForkNumber forkNum)\n+{\n+ return (int64)table_relation_size(rel, forkNum);\n+}\nWhy isn't that just unsigned, like table_relation_size()? This is an\ninternal function so it does not matter to changes its signature, but\nI think that you had better do a cast at a higher level instead.\n\n for (int i = 0; i < MAX_FORKNUM; i++)\n- nblocks += smgrnblocks(rel->rd_smgr, i);\n+ nblocks += smgrexists(rel->rd_smgr, i)\n+ ? smgrnblocks(rel->rd_smgr, i)\n+ : 0;\nIs that actually the part for views? Why is that done this way?\n\n+ if (rel->rd_rel->relkind == RELKIND_RELATION ||\n+ rel->rd_rel->relkind == RELKIND_TOASTVALUE ||\n+ rel->rd_rel->relkind == RELKIND_MATVIEW)\n+ size = calculate_table_fork_size(rel,\n+ forkname_to_number(text_to_cstring(forkName)));\n+ else if (rel->rd_rel->relkind == RELKIND_INDEX)\n+ size = calculate_relation_size(&(rel->rd_node), rel->rd_backend,\n+ forkname_to_number(text_to_cstring(forkName)));\n+ else\n+ {\n+ relation_close(rel, AccessShareLock);\n+ PG_RETURN_NULL();\n+ }\nThe approach you are taking to bring some consistency in all that by\nmaking the size estimations go through table AMs via\ntable_relation_size() is promising. However, this code breaks the\nsize estimation for sequences, which is not good. If attempting to\nuse an evaluation that's based on a table AM, shouldn't this code use\na check based on rd_tableam rather than the relkind then? We assume\nthat rd_tableam is set depending on the relkind in relcache.c, for\none.\n--\nMichael", "msg_date": "Mon, 15 Mar 2021 15:10:59 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": "‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn Monday, March 15, 2021 7:10 AM, Michael Paquier <michael@paquier.xyz> wrote:\n\n&gt; On Wed, Feb 24, 2021 at 02:35:51PM +0000, gkokolatos@pm.me wrote:\n&gt;\n&gt; &gt; Now with attachment. Apologies for the chatter.\n&gt;\n&gt; The patch has no documentation for the two new functions, so it is a\n&gt; bit hard to understand what is the value brought here, and what is the\n&gt; goal wanted just by reading the patch, except that this switches the\n&gt; size reported for views to NULL instead of zero bytes by reading the\n&gt; regression tests.\n\nUnderstood and agreed. Thank you very much for looking.\n\n&gt;\n&gt; Please note that reporting zero is not wrong for views IMO as these\n&gt; have no physical storage, so, while it is possible to argue that a\n&gt; size of zero could imply that this relation size could not be zero, it\n&gt; will never change, so I'd rather let this behavior as it is. I\n&gt; would bet, additionally, that this could break existing use cases.\n&gt; Reporting NULL, on the contrary, as your patch does, makes things\n&gt; worse in some ways because that's what pg_relation_size would report\n&gt; when a relation does not exist anymore. Imagine for example the case\n&gt; of a DROP TABLE run in parallel of a scan of pg_class using\n&gt; pg_relation_size(). So it becomes impossible to know if a relation\n&gt; has been removed or not. This joins some points raised by Soumyadeep\n&gt; upthread.\n\nYeah, I would have agreed with you before actually looking a bit closer.\nI think that the gist of it is that the intention of the functions and\nthe actual usage/documentation of those have diverged. I honestly thought\nthat pg_relation_size() was a general function intended for any kind of\nrelation, whereas pg_table_size() was a function intended only for tables\n(toast and mat views included).\n\nThen I read the comment describing pg_relation_size() which reads\n'disk space usage for the main fork of the specified table or index' and\n'disk space usage for the specified fork of a table or index', found\ninitially in commit 358a897fa1d and maintained since.\n\nBut I digress.\n\n\n&gt;\n&gt; Anyway, as mentioned by other people upthread, I am not really\n&gt; convinced either that we should have more flavors of size functions,\n&gt; particularly depending on the relkind as this would be confusing for\n&gt; the end-user. pg_relation_size() can already do this job for all\n&gt; relkinds that use segment files, so it should still be able to hold\n&gt; its ground and maintain a consistent behavior with what it does\n&gt; currently.\n\nI must have missunderstood the other people upthread and I thought\nthat new flavours were requested. Thank you for clarifying and\ncorrecting me.\n\n&gt;\n&gt; +static int64\n&gt; +calculate_table_fork_size(Relation rel, ForkNumber forkNum)\n&gt; +{\n&gt;\n&gt; - return (int64)table_relation_size(rel, forkNum);\n&gt; +}\n&gt; Why isn't that just unsigned, like table_relation_size()? This is an\n&gt; internal function so it does not matter to changes its signature, but\n&gt; I think that you had better do a cast at a higher level instead.\n&gt;\n&gt; for (int i = 0; i &lt; MAX_FORKNUM; i++)\n&gt;\n&gt;\n&gt; - nblocks += smgrnblocks(rel-&gt;rd_smgr, i);\n&gt;\n&gt;\n&gt;\n&gt; - nblocks += smgrexists(rel-&gt;rd_smgr, i)\n&gt;\n&gt;\n&gt; - ? smgrnblocks(rel-&gt;rd_smgr, i)\n&gt;\n&gt;\n&gt; - : 0;\n&gt;\n&gt;\n&gt;\n&gt; Is that actually the part for views? Why is that done this way?\n\nNo, it is not for views. The codebase should never reach this function\nfor a view or it would be a serious bug elsewhere.\n\nThis is addressing a bug in table_relation_size(). This function is correctly\nnot requiring for its caller to know any specifics about the forks. A heap\ntable is not required to have created any fsm, or vm, forks neither. Finally\nsmgrnblocks() assumes that the fork actually exists or errors out.\n\nThis change, makes certain that calling table_relation_size() with a\nnon existing fork will not generate an error.\n\n&gt;\n&gt; - if (rel-&gt;rd_rel-&gt;relkind == RELKIND_RELATION ||\n&gt;\n&gt; - rel-&gt;rd_rel-&gt;relkind == RELKIND_TOASTVALUE ||\n&gt;\n&gt;\n&gt; - rel-&gt;rd_rel-&gt;relkind == RELKIND_MATVIEW)\n&gt;\n&gt;\n&gt; - size = calculate_table_fork_size(rel,\n&gt;\n&gt;\n&gt; - forkname_to_number(text_to_cstring(forkName)));\n&gt;\n&gt;\n&gt; - else if (rel-&gt;rd_rel-&gt;relkind == RELKIND_INDEX)\n&gt;\n&gt; - size = calculate_relation_size(&amp;(rel-&gt;rd_node), rel-&gt;rd_backend,\n&gt;\n&gt;\n&gt; - forkname_to_number(text_to_cstring(forkName)));\n&gt;\n&gt;\n&gt; - else\n&gt;\n&gt; - {\n&gt;\n&gt; - relation_close(rel, AccessShareLock);\n&gt;\n&gt;\n&gt; - PG_RETURN_NULL();\n&gt;\n&gt;\n&gt; - }\n&gt; The approach you are taking to bring some consistency in all that by\n&gt; making the size estimations go through table AMs via\n&gt; table_relation_size() is promising. However, this code breaks the\n&gt; size estimation for sequences, which is not good. If attempting to\n&gt; use an evaluation that's based on a table AM, shouldn't this code use\n&gt; a check based on rd_tableam rather than the relkind then? We assume\n&gt; that rd_tableam is set depending on the relkind in relcache.c, for\n&gt; one.\n\n\nThank you for the remarks. Please find v5 attached which is a minimal\npatch to try to use the table am api if the relation is using the table\nam api. Otherwise all else remains the same.\n\nCheers,\nGeorgios\n\n\n&gt; --\n&gt; Michael\n&gt;\n\n</michael@paquier.xyz>", "msg_date": "Mon, 15 Mar 2021 12:18:12 +0000", "msg_from": "gkokolatos@pm.me", "msg_from_op": true, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": "On Mon, Mar 15, 2021 at 03:10:59PM +0900, Michael Paquier wrote:\n> Anyway, as mentioned by other people upthread, I am not really\n> convinced either that we should have more flavors of size functions,\n> particularly depending on the relkind as this would be confusing for\n> the end-user. pg_relation_size() can already do this job for all\n> relkinds that use segment files, so it should still be able to hold\n> its ground and maintain a consistent behavior with what it does\n> currently.\n\nOn top of the rest of my notes, there are two more things that would\nface a behavior change if making the existing functions go through\ntable AMs, which would scan the data in the smgr:\n- After a VACUUM, the relation would be reported with a size of 0,\nwhile that may not be the case of on-disk files yet.\n- Temporary tables of other sessions would be accessible.\n\nSo we would likely want a separate function. Another possibility,\nwhich I find tempting, would be to push down the calculation logic\nrelying on physical files down to the table AM themselves with a new\ndedicated callback (relation_size_physical?), as it seems to me that\nthe most important thing users want to know with this set of functions\nis how much physical space is being consumed at one given point in\ntime. Attached is a small prototype I was just playing with.\n--\nMichael", "msg_date": "Wed, 17 Mar 2021 14:35:28 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": "\n\n\n\n\n‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn Wednesday, March 17, 2021 6:35 AM, Michael Paquier <michael@paquier.xyz> wrote:\n\n> On Mon, Mar 15, 2021 at 03:10:59PM +0900, Michael Paquier wrote:\n>\n> > Anyway, as mentioned by other people upthread, I am not really\n> > convinced either that we should have more flavors of size functions,\n> > particularly depending on the relkind as this would be confusing for\n> > the end-user. pg_relation_size() can already do this job for all\n> > relkinds that use segment files, so it should still be able to hold\n> > its ground and maintain a consistent behavior with what it does\n> > currently.\n>\n> On top of the rest of my notes, there are two more things that would\n> face a behavior change if making the existing functions go through\n> table AMs, which would scan the data in the smgr:\n\nI am not certain if you are referring to v5 (sent earlier than your mail)\nor v4. Can you please verify?\n\n>\n> - After a VACUUM, the relation would be reported with a size of 0,\n> while that may not be the case of on-disk files yet.\n\nI am not really following. Apologies for it. The table AM may or may not\nchoose to go through smgr, depending on the implementation. The only\ncurrently known implementation, heap, does invalidate smgr, based on\nwhat I can see, after a VACUUM. I have not been able to create a test\ncase both with or without v5 of the patch where not the same result\nwould be returned.\n\nWhat have I missed?\n\n>\n> - Temporary tables of other sessions would be accessible.\n\nI am not really certain I am following. Commit 6919b7e3294 from 2012\nnotes that calculate_relation_size can be safely applied to temp tables\nof other sessions. v5 of the patch does not change that behaviour. Nor\ndid previous versions, but those are already obsolete.\n\n>\n> So we would likely want a separate function. Another possibility,\n> which I find tempting, would be to push down the calculation logic\n> relying on physical files down to the table AM themselves with a new\n> dedicated callback (relation_size_physical?), as it seems to me that\n> the most important thing users want to know with this set of functions\n> is how much physical space is being consumed at one given point in\n> time. Attached is a small prototype I was just playing with.\n> --\n> Michael\n>\n\n\n\n\n", "msg_date": "Tue, 23 Mar 2021 13:06:17 +0000", "msg_from": "gkokolatos@pm.me", "msg_from_op": true, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" }, { "msg_contents": "On Wed, Mar 17, 2021 at 02:35:28PM +0900, Michael Paquier wrote:\n> So we would likely want a separate function. Another possibility,\n> which I find tempting, would be to push down the calculation logic\n> relying on physical files down to the table AM themselves with a new\n> dedicated callback (relation_size_physical?), as it seems to me that\n> the most important thing users want to know with this set of functions\n> is how much physical space is being consumed at one given point in\n> time. Attached is a small prototype I was just playing with.\n\nThinking more about that, I'd be rather in favor of having a new table\nAM callback to let the AM measure the size of physical files, and make\nthe business of dbsize.c fall under that. It is clear that this needs\nmore work, so I have marked it as returned with feedback.\n--\nMichael", "msg_date": "Thu, 8 Apr 2021 17:04:35 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: PATCH: Attempt to make dbsize a bit more consistent" } ]
[ { "msg_contents": "Hackers,\n\nOver in [1] we have been discussing the deprecation of postfix operators, with the general consensus that deprecation warnings should be included in this upcoming release and postfix operator support should be removed in PostgreSQL 14. Since not all people who follow -hackers will necessarily have been following that thread, I am creating this new thread, with a patch which adds the deprecation notices, for your consideration.\n \nThe only postfix operator we ship in the standard catalogs is the factorial operator (!), which is deprecated by this patch.\n\nThe standard catalogs also include a prefix factorial operator (!!) which has been deprecated since 2011.\n\nThe deprecation warnings included in this patch warn that postfix operator support, along with both postfix ! and prefix !! factorial operators, will be removed in PostgreSQL 14.\n\nSome of the deprecation verbiage supplied by John Naylor, some by me:\n\n\n\n\n\n[1] https://www.postgresql.org/message-id/flat/20200519145449.GN13712%40tamriel.snowman.net#34294baed8757c8e078550b9ba80081d\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company", "msg_date": "Thu, 27 Aug 2020 09:13:49 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Deprecating postfix and factorial operators in PostgreSQL 13" }, { "msg_contents": "Mark Dilger <mark.dilger@enterprisedb.com> writes:\n> The deprecation warnings included in this patch warn that postfix operator support, along with both postfix ! and prefix !! factorial operators, will be removed in PostgreSQL 14.\n\nThe operator docs should say \"use factorial() instead\", or words to\nthat effect.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 27 Aug 2020 12:16:22 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Deprecating postfix and factorial operators in PostgreSQL 13" }, { "msg_contents": "> On Aug 27, 2020, at 9:16 AM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> Mark Dilger <mark.dilger@enterprisedb.com> writes:\n>> The deprecation warnings included in this patch warn that postfix operator support, along with both postfix ! and prefix !! factorial operators, will be removed in PostgreSQL 14.\n> \n> The operator docs should say \"use factorial() instead\", or words to\n> that effect.\n> \n> \t\t\tregards, tom lane\n\nYes, that is better. Attached.\n\n\n\n\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company", "msg_date": "Thu, 27 Aug 2020 10:07:34 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Deprecating postfix and factorial operators in PostgreSQL 13" }, { "msg_contents": "Hi Mark,\n\n-{ oid => '111',\n+{ oid => '111', descr => 'factorial',\n\nI see that opr_sanity fails without something here. We explicitly\ndon't have descriptions of functions that implement deprecated\noperators (see setup_description() in initdb.c), but in all other\ncases, there are also supported operators present. Technically, it's\nnot the same entry as the sql-callable function (1376), so it might be\nbetter to try to match the other operator functions and say\n\"implementation of deprecated ! and !! operators\".\n\nFor typeconv.sgml, it looks like in v14 we'll just have a different\noperator entirely for the example, so ideally we would backpatch that\nchange for v13. What you have is good enough in a pinch, though.\n\n--\nJohn Naylor https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 28 Aug 2020 11:24:40 +0300", "msg_from": "John Naylor <john.naylor@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Deprecating postfix and factorial operators in PostgreSQL 13" }, { "msg_contents": "On Thu, Aug 27, 2020 at 1:07 PM Mark Dilger\n<mark.dilger@enterprisedb.com> wrote:\n> Yes, that is better. Attached.\n\nSo, in this version, there are six copies of the deprecation notice\nJohn wrote, rather than just one. Maybe we need more than one, but I\ndoubt we need six. I don't think the CREATE OPERATOR documentation\nneeds to mention this both when first introducing the concept and then\nagain when defining right_type; the former seems sufficient. I don't\nthink xoper.sgml needs these changes either; they interrupt the flow\nof the narrative and I don't think this is where anyone would look for\na deprecation notice. I would also argue for dropping the mentions in\nthe docs for ALTER OPERATOR FAMILY and CREATE OPERATOR CLASS, although\nthose seem less clear-cut. Really, CREATE OPERATOR where John had it\noriginally seems like the right place.\n\nThat being said, the changes to typeconv.sgml and drop_operator.sgml\nseem like improvements, so I'd keep those.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Fri, 28 Aug 2020 11:17:12 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Deprecating postfix and factorial operators in PostgreSQL 13" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> So, in this version, there are six copies of the deprecation notice\n> John wrote, rather than just one. Maybe we need more than one, but I\n> doubt we need six. I don't think the CREATE OPERATOR documentation\n> needs to mention this both when first introducing the concept and then\n> again when defining right_type; the former seems sufficient. I don't\n> think xoper.sgml needs these changes either; they interrupt the flow\n> of the narrative and I don't think this is where anyone would look for\n> a deprecation notice. I would also argue for dropping the mentions in\n> the docs for ALTER OPERATOR FAMILY and CREATE OPERATOR CLASS, although\n> those seem less clear-cut. Really, CREATE OPERATOR where John had it\n> originally seems like the right place.\n\nYeah, I agree that there are way too many copies here. CREATE OPERATOR\nseems sufficient. It also seems like we should just rewrite the typeconv\nand drop_operator examples to use some other operator. We'll have\nto do that eventually anyway, so why not now, instead of visiting those\nplaces twice?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 28 Aug 2020 11:56:26 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Deprecating postfix and factorial operators in PostgreSQL 13" }, { "msg_contents": "On Fri, Aug 28, 2020 at 11:56 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Yeah, I agree that there are way too many copies here. CREATE OPERATOR\n> seems sufficient. It also seems like we should just rewrite the typeconv\n> and drop_operator examples to use some other operator. We'll have\n> to do that eventually anyway, so why not now, instead of visiting those\n> places twice?\n\nHmm, that's an idea. I think it would be reasonable to rewrite the\ntypeconv.sgml one, but the one in drop_operator.sgml seems like it\ncould just be dropped. Its only purpose seems to be to demonstrate how\nto drop a right-unary operator vs. a left-unary operator, but I\nventure to guess that anyone smart enough to make any sort of\neffective use of DROP OPERATOR could probably draw the necessary\ninferences anyway.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Fri, 28 Aug 2020 12:43:16 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Deprecating postfix and factorial operators in PostgreSQL 13" }, { "msg_contents": "> On Aug 28, 2020, at 8:56 AM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> Robert Haas <robertmhaas@gmail.com> writes:\n>> So, in this version, there are six copies of the deprecation notice\n>> John wrote, rather than just one. Maybe we need more than one, but I\n>> doubt we need six. I don't think the CREATE OPERATOR documentation\n>> needs to mention this both when first introducing the concept and then\n>> again when defining right_type; the former seems sufficient. I don't\n>> think xoper.sgml needs these changes either; they interrupt the flow\n>> of the narrative and I don't think this is where anyone would look for\n>> a deprecation notice. I would also argue for dropping the mentions in\n>> the docs for ALTER OPERATOR FAMILY and CREATE OPERATOR CLASS, although\n>> those seem less clear-cut. Really, CREATE OPERATOR where John had it\n>> originally seems like the right place.\n> \n> Yeah, I agree that there are way too many copies here. CREATE OPERATOR\n> seems sufficient. It also seems like we should just rewrite the typeconv\n> and drop_operator examples to use some other operator. We'll have\n> to do that eventually anyway, so why not now, instead of visiting those\n> places twice?\n\nJohn's deprecation language now only appears in the create operator documentation.\n\nThe first typeconv example was based on the (int8 !) operator. I chose to replace it with and example based on the (jsonb ? text) operator, as the two operators have a relevant similarity. Both of them are singletons, with only one interpretation in the standard catalogs. In both cases, the scanner cannot know the types of the undecorated arguments and assigns default types (integer and unknown, respectively), which get resolved later to match the only types accepted by the operator ('int8' for !, and 'jsonb,text' for ?).\n\nThe drop operator example has been left, though altered to include the adjective \"deprecated\". Robert mentions that the entire example could simply be dropped now, and I agree with that, but it also makes sense to me to drop the example in 14, when the operation it describes is also dropped. If the committer who picks this up wants to drop that example now, that's fine, too.\n\n\n\n\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company", "msg_date": "Sun, 30 Aug 2020 09:55:19 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Deprecating postfix and factorial operators in PostgreSQL 13" }, { "msg_contents": "Mark Dilger <mark.dilger@enterprisedb.com> writes:\n> [ v3-0001-Adding-deprecation-notices.patch ]\n\nPushed with some fiddling.\n\nWe previously found that adding id tags to <entry> constructs in the\nfunction lists didn't work in PDF output [1]. Your patch did build\na PDF without warnings for me, which is odd --- apparently we changed\nsomething since April? But the links didn't lead to quite the right\nplace, so the conclusion that there's something broken with that still\nholds. I made it look like the existing usages for encode() and decode().\n\nI did not like your choice of \"jsonb ? text\" for the typeconv example\nat all, primarily because it introduces a host of distractions for anyone\nwho's not already quite familiar with both JSON and that operator.\nAfter some digging around I found the |/ (square root) operator, which\nlikewise has just one instance, and it's something familiar enough that\nmost readers probably won't be slowed down by trying to figure out what\nit does. Also, this more nearly covers the territory of the original\nexample, namely auto-casting an integer constant to something else.\nThere are later examples covering unknown-type literals, so we don't\nneed to address that scenario in this one.\n\nI also found another example that depends on the ! operator, in the\noperator precedence discussion. I concluded after study that the\nparticular case it's on about only arises for postfix operators,\nso I just got rid of that example in favor of a generalized mention\nthat you should use parentheses to override operator precedence.\n\nI concluded that there's not much point in touching drop_operator.sgml\nat all yet. I don't think labeling ! as deprecated as adding anything\nto that example, and besides there's another example that will also need\nto be changed.\n\n\t\t\tregards, tom lane\n\n[1] https://www.postgresql.org/message-id/32159.1586738304%40sss.pgh.pa.us\n\n\n", "msg_date": "Sun, 30 Aug 2020 14:50:07 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Deprecating postfix and factorial operators in PostgreSQL 13" }, { "msg_contents": "\n\n> On Aug 30, 2020, at 11:50 AM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> Mark Dilger <mark.dilger@enterprisedb.com> writes:\n>> [ v3-0001-Adding-deprecation-notices.patch ]\n> \n> Pushed with some fiddling.\n\nThanks!\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Mon, 31 Aug 2020 07:25:21 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Deprecating postfix and factorial operators in PostgreSQL 13" } ]
[ { "msg_contents": "If I create a large table with \"CREATE TABLE ... AS SELECT ... from\ngenerate_series(1,3e7)\" with no explicit transactions, then once it is done\nI wait for autovac to kick in, then when I try to build an index on that\ntable (or drop the table) the autovac doesn't go away on its own.\n\nBisects down to:\n\ncommit 5788e258bb26495fab65ff3aa486268d1c50b123\nAuthor: Andres Freund <andres@anarazel.de>\nDate: Wed Jul 15 15:35:07 2020 -0700\n\n snapshot scalability: Move PGXACT->vacuumFlags to\nProcGlobal->vacuumFlags.\n\nWhich makes sense given the parts of the code this touches, although I\ndon't understand exactly what the problem is. The problem persists in HEAD\n(77c7267c37).\n\nCheers,\n\nJeff\n\nIf I create a large table with \"CREATE TABLE ... AS SELECT ... from generate_series(1,3e7)\" with no explicit transactions, then once it is done I wait for autovac to kick in, then when I try to build an index on that table (or drop the table) the autovac doesn't go away on its own.Bisects down to:commit 5788e258bb26495fab65ff3aa486268d1c50b123Author: Andres Freund <andres@anarazel.de>Date:   Wed Jul 15 15:35:07 2020 -0700    snapshot scalability: Move PGXACT->vacuumFlags to ProcGlobal->vacuumFlags.Which makes sense given the parts of the code this touches, although I don't understand exactly what the problem is.  The problem persists in HEAD (77c7267c37).Cheers,Jeff", "msg_date": "Thu, 27 Aug 2020 15:10:47 -0400", "msg_from": "Jeff Janes <jeff.janes@gmail.com>", "msg_from_op": true, "msg_subject": "Autovac cancellation is broken in v14" }, { "msg_contents": "On Thu, Aug 27, 2020 at 3:10 PM Jeff Janes <jeff.janes@gmail.com> wrote:\n\n> If I create a large table with \"CREATE TABLE ... AS SELECT ... from\n> generate_series(1,3e7)\" with no explicit transactions, then once it is done\n> I wait for autovac to kick in, then when I try to build an index on that\n> table (or drop the table) the autovac doesn't go away on its own.\n>\n\nAfter a bit more poking at this, I think we are checking if we ourselves\nare an autovac process, not doing the intended check of whether the other\nguy is one.\n\nWhere would be a good spot to add a regression test for this?\n\"isolation_regression\" ?\nCheers,\n\nJeff", "msg_date": "Thu, 27 Aug 2020 16:20:30 -0400", "msg_from": "Jeff Janes <jeff.janes@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Autovac cancellation is broken in v14" }, { "msg_contents": "Hi,\n\nOn 2020-08-27 16:20:30 -0400, Jeff Janes wrote:\n> On Thu, Aug 27, 2020 at 3:10 PM Jeff Janes <jeff.janes@gmail.com> wrote:\n> \n> > If I create a large table with \"CREATE TABLE ... AS SELECT ... from\n> > generate_series(1,3e7)\" with no explicit transactions, then once it is done\n> > I wait for autovac to kick in, then when I try to build an index on that\n> > table (or drop the table) the autovac doesn't go away on its own.\n> >\n> \n> After a bit more poking at this, I think we are checking if we ourselves\n> are an autovac process, not doing the intended check of whether the other\n> guy is one.\n\nUgh, good catch.\n\n\n> Where would be a good spot to add a regression test for this?\n> \"isolation_regression\" ?\n\nI'm not immediately sure how we could write a good test for this,\nparticularly not in the isolation tests. We'd basically have to make\nsure that a table needs autovacuuming, then sleep for long enough for\nautovacuum to have come around, and block autovacuum from making\nprogress. That latter is doable by holding a pin on a page it needs to\nfreeze, e.g. using a cursor. I suspect all of that would at least\nrequire a TAP test, and might still be too fragile.\n\nOther ideas?\n\nRegards,\n\nAndres\n\n\n", "msg_date": "Thu, 27 Aug 2020 14:35:06 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Autovac cancellation is broken in v14" }, { "msg_contents": "Hi,\n\nOn 2020-08-27 14:35:06 -0700, Andres Freund wrote:\n> On 2020-08-27 16:20:30 -0400, Jeff Janes wrote:\n> > On Thu, Aug 27, 2020 at 3:10 PM Jeff Janes <jeff.janes@gmail.com> wrote:\n> > \n> > > If I create a large table with \"CREATE TABLE ... AS SELECT ... from\n> > > generate_series(1,3e7)\" with no explicit transactions, then once it is done\n> > > I wait for autovac to kick in, then when I try to build an index on that\n> > > table (or drop the table) the autovac doesn't go away on its own.\n> > >\n> > \n> > After a bit more poking at this, I think we are checking if we ourselves\n> > are an autovac process, not doing the intended check of whether the other\n> > guy is one.\n> \n> Ugh, good catch.\n\nPushed the fix.\n\n\n> > Where would be a good spot to add a regression test for this?\n> > \"isolation_regression\" ?\n> \n> I'm not immediately sure how we could write a good test for this,\n> particularly not in the isolation tests. We'd basically have to make\n> sure that a table needs autovacuuming, then sleep for long enough for\n> autovacuum to have come around, and block autovacuum from making\n> progress. That latter is doable by holding a pin on a page it needs to\n> freeze, e.g. using a cursor. I suspect all of that would at least\n> require a TAP test, and might still be too fragile.\n\nPerhaps the easiest way for this would be to have an option to have\nmanual VACUUMs be interruptible by other backends. That seems like a\nuseful option anyway? I'll start a new thread.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 8 Sep 2020 11:35:29 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Autovac cancellation is broken in v14" } ]
[ { "msg_contents": "Hi,\n\nPer Coverity.\n\nWhen \"Prepare for toasting\", it is necessary to turn off the flag\nTOAST_NEEDS_DELETE_OLD,\nif there is no need to delete external values from the old tuple, otherwise,\nthere are dereference NULL at toast_helper.c (on toast_tuple_cleanup\nfunction).\n\n\nregards,\nRanier Vilela", "msg_date": "Thu, 27 Aug 2020 21:22:47 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "[PATCH] Explicit null dereferenced\n (src/backend/access/heap/heaptoast.c)" }, { "msg_contents": "\n\n\n\n\n‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn Friday, 28 August 2020 03:22, Ranier Vilela <ranier.vf@gmail.com> wrote:\n\n> Hi,\n>\n> Per Coverity.\n>\n> When \"Prepare for toasting\", it is necessary to turn off the flag TOAST_NEEDS_DELETE_OLD,\n> if there is no need to delete external values from the old tuple, otherwise,\n> there are dereference NULL at toast_helper.c (on toast_tuple_cleanup function).\n>\n\nExcuse my ignorance, isn't this a false positive?\n\nRegardless right after prepare for toasting, a call to toast_tuple_init is made which will explicitly and unconditionally set ttc_flags to zero so the flag bit set in the patch will be erased anyways. This patch may make coverity happy but does not really change anything in the behaviour of the code.\n\nFurthermore, in the same function, toast_tuple_init, the flag is set to TOAST_NEEDS_DELETE_OLD after the old value is actually inspected and found to not be null, be stored on disk and to be different than the new value. To my understanding, this seems to be correct.\n\nCan you please explain to me what I am missing?\n\n//Georgios\n\n> regards,\n> Ranier Vilela\n\n\n\n\n", "msg_date": "Fri, 28 Aug 2020 07:44:50 +0000", "msg_from": "gkokolatos@pm.me", "msg_from_op": false, "msg_subject": "Re: [PATCH] Explicit null dereferenced\n (src/backend/access/heap/heaptoast.c)" }, { "msg_contents": "Em sex., 28 de ago. de 2020 às 04:45, <gkokolatos@pm.me> escreveu:\n\n>\n>\n>\n>\n>\n> ‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\n> On Friday, 28 August 2020 03:22, Ranier Vilela <ranier.vf@gmail.com>\n> wrote:\n>\n> > Hi,\n> >\n> > Per Coverity.\n> >\n> > When \"Prepare for toasting\", it is necessary to turn off the flag\n> TOAST_NEEDS_DELETE_OLD,\n> > if there is no need to delete external values from the old tuple,\n> otherwise,\n> > there are dereference NULL at toast_helper.c (on toast_tuple_cleanup\n> function).\n> >\n>\n> Excuse my ignorance, isn't this a false positive?\n>\nYes, you're right.\n\nCoverity fails with &.\n\nif (oldtup == NULL)\n147 {\n\n3. assign_zero: Assigning: ttc.ttc_oldvalues = NULL.\n148 ttc.ttc_oldvalues = NULL;\n149 ttc.ttc_oldisnull = NULL;\n\n4. Falling through to end of if statement.\n150 }\n151 else\n152 {\n153 ttc.ttc_oldvalues = toast_oldvalues;\n154 ttc.ttc_oldisnull = toast_oldisnull;\n155 }\n156 ttc.ttc_attr = toast_attr;\n157 toast_tuple_init(&ttc); // Coverity ignores the call completely\nhere.\n\ntoast_tuple_init, solves the bug, because reset ttc->flags.\n\n\n> Regardless right after prepare for toasting, a call to toast_tuple_init is\n> made which will explicitly and unconditionally set ttc_flags to zero so the\n> flag bit set in the patch will be erased anyways. This patch may make\n> coverity happy but does not really change anything in the behaviour of the\n> code.\n>\nThat's right, the patch doesn't change anything.\n\n\n>\n> Furthermore, in the same function, toast_tuple_init, the flag is set to\n> TOAST_NEEDS_DELETE_OLD after the old value is actually inspected and found\n> to not be null, be stored on disk and to be different than the new value.\n> To my understanding, this seems to be correct.\n>\nVery correct.\n\nThanks for taking a look here.\n\nYou could take a look at the attached patch,\nwould it be an improvement?\ntoast_tuple_init, it seems to me that it can be improved.\nttc->ttc_oldvalues is constant, and it could be unlooping?\n\nregards,\nRanier Vilela", "msg_date": "Fri, 28 Aug 2020 10:24:23 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Re: [PATCH] Explicit null dereferenced\n (src/backend/access/heap/heaptoast.c)" } ]
[ { "msg_contents": "We have a Postgres 13 open item for Disk-based hash aggregate, which\nis the only non-trivial open item. There is a general concern about\nhow often we get disk-based hash aggregation when work_mem is\nparticularly low, and recursion seems unavoidable. This is generally\nthought to be a problem in the costing.\n\nTomas Vondra did some testing of the patch which led to discussion of\nthis on the hash agg GUC megathread, here:\n\nhttps://www.postgresql.org/message-id/20200724012248.y77rpqc73agrsvb3@development\n\nI am starting this new thread to deal with the open item.\n\nAny progress on this, Jeff? Please correct or expand on my summary of\nthe open item if I got something wrong.\n\nThanks\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Thu, 27 Aug 2020 17:28:20 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Disk-based hash aggregate's cost model" }, { "msg_contents": "On Thu, 2020-08-27 at 17:28 -0700, Peter Geoghegan wrote:\n> We have a Postgres 13 open item for Disk-based hash aggregate, which\n> is the only non-trivial open item. There is a general concern about\n> how often we get disk-based hash aggregation when work_mem is\n> particularly low, and recursion seems unavoidable. This is generally\n> thought to be a problem in the costing.\n\nWe discussed two approaches to tweaking the cost model:\n\n1. Penalize HashAgg disk costs by a constant amount. It seems to be\nchosen a little too often, and we can reduce the number of plan\nchanges.\n\n2. Treat recursive HashAgg spilling skeptically, and heavily penalize\nrecursive spilling.\n\nThe problem with approach #2 is that we have a default hash mem of 4MB,\nand real systems have a lot more than that. In this scenario, recursive\nspilling can beat Sort by a lot.\n\nFor instance:\n\nData:\n create table text10m(t text collate \"C.UTF-8\", i int, n numeric);\n insert into t10m\n select s.g::text, s.g, s.g::numeric\n from (\n select (random()*1000000000)::int as g\n from generate_series(1,10000000)) s;\n vacuum (freeze,analyze) text10m;\n\nQuery: explain analyze select distinct t from text10m;\n\nHashAgg: 10.5s\nSort+Distinct: 46s\n\nI'm inclined toward option #1 for simplicity unless you feel strongly\nabout option #2. Specifically, I was thinking of a 1.5X penalty for\nHashAgg disk costs.\n\nRegards,\n\tJeff Davis\n\n\n\n\n", "msg_date": "Fri, 28 Aug 2020 18:32:38 -0700", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: Disk-based hash aggregate's cost model" }, { "msg_contents": "On Fri, Aug 28, 2020 at 06:32:38PM -0700, Jeff Davis wrote:\n>On Thu, 2020-08-27 at 17:28 -0700, Peter Geoghegan wrote:\n>> We have a Postgres 13 open item for Disk-based hash aggregate, which\n>> is the only non-trivial open item. There is a general concern about\n>> how often we get disk-based hash aggregation when work_mem is\n>> particularly low, and recursion seems unavoidable. This is generally\n>> thought to be a problem in the costing.\n>\n>We discussed two approaches to tweaking the cost model:\n>\n>1. Penalize HashAgg disk costs by a constant amount. It seems to be\n>chosen a little too often, and we can reduce the number of plan\n>changes.\n>\n>2. Treat recursive HashAgg spilling skeptically, and heavily penalize\n>recursive spilling.\n>\n>The problem with approach #2 is that we have a default hash mem of 4MB,\n>and real systems have a lot more than that. In this scenario, recursive\n>spilling can beat Sort by a lot.\n>\n\nI think the main issue is that we're mostly speculating what's wrong.\nI've shared some measurements and symptoms, and we've discussed what\nmight be causing it, but I'm not really sure we know for sure.\n\nI really dislike (1) because it seems more like \"We don't know what's\nwrong so we'll penalize hashagg,\" kind of solution. A much more\nprincipled solution would be to tweak the costing accordingly, not just\nby adding some constant. For (2) it really depends if recursive spilling\nis really the problem here. In the examples I shared, the number of\npartitions/batches was very different, but the query duration was\nmostly independent (almost constant).\n\n\nFWIW I still haven't seen any explanation why the current code spills\nmore data than the CP_SMALL_TLIST patch (which was reverted).\n\n\nregards\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Sun, 30 Aug 2020 02:26:20 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Disk-based hash aggregate's cost model" }, { "msg_contents": "On Sun, Aug 30, 2020 at 02:26:20AM +0200, Tomas Vondra wrote:\n>On Fri, Aug 28, 2020 at 06:32:38PM -0700, Jeff Davis wrote:\n>>On Thu, 2020-08-27 at 17:28 -0700, Peter Geoghegan wrote:\n>>>We have a Postgres 13 open item for Disk-based hash aggregate, which\n>>>is the only non-trivial open item. There is a general concern about\n>>>how often we get disk-based hash aggregation when work_mem is\n>>>particularly low, and recursion seems unavoidable. This is generally\n>>>thought to be a problem in the costing.\n>>\n>>We discussed two approaches to tweaking the cost model:\n>>\n>>1. Penalize HashAgg disk costs by a constant amount. It seems to be\n>>chosen a little too often, and we can reduce the number of plan\n>>changes.\n>>\n>>2. Treat recursive HashAgg spilling skeptically, and heavily penalize\n>>recursive spilling.\n>>\n>>The problem with approach #2 is that we have a default hash mem of 4MB,\n>>and real systems have a lot more than that. In this scenario, recursive\n>>spilling can beat Sort by a lot.\n>>\n>\n>I think the main issue is that we're mostly speculating what's wrong.\n>I've shared some measurements and symptoms, and we've discussed what\n>might be causing it, but I'm not really sure we know for sure.\n>\n>I really dislike (1) because it seems more like \"We don't know what's\n>wrong so we'll penalize hashagg,\" kind of solution. A much more\n>principled solution would be to tweak the costing accordingly, not just\n>by adding some constant. For (2) it really depends if recursive spilling\n>is really the problem here. In the examples I shared, the number of\n>partitions/batches was very different, but the query duration was\n>mostly independent (almost constant).\n>\n\nI've decided to look at the costing a bit more closely today, and see\nwhy the costing is so much lower compared to sort/groupagg. I've used\nthe same 32GB dataset and query as in [1].\n\nI've repeated tests for all the work_mem values, and I see the number of\nbatches are much lower, probably thanks to the HLL improvement:\n\n 2MB Planned: 64 Batches (old): 4160 Batches: 2977\n 4MB Planned: 128 Batches (old): 16512 Batches: 1569\n 8MB Planned: 256 Batches (old): 21488 Batches: 1289\n 64MB Planned: 32 Batches (old): 2720 Batches: 165\n 256MB Planned: 8 Batches (old): 8 Batches: 41\n\nThe impact on duration of the queries seems pretty negligible, though.\n\n\nThe plans with work_mem=64MB look like this:\n\n1) hashagg\n\n QUERY PLAN\n----------------------------------------------------------------------------------------------------------------------------------------\n Limit (cost=11267293.86..11267293.86 rows=1 width=36) (actual time=213127.515..213127.517 rows=0 loops=1)\n -> HashAggregate (cost=10229061.10..11267293.86 rows=6718533 width=36) (actual time=100862.623..212948.642 rows=6400000 loops=1)\n Group Key: lineitem.l_partkey\n Planned Partitions: 32 Batches: 165 Memory Usage: 67857kB Disk Usage: 6802432kB\n -> Seq Scan on lineitem (cost=0.00..5519288.36 rows=191990736 width=9) (actual time=0.418..20344.631 rows=192000551 loops=1)\n Planning Time: 0.064 ms\n Execution Time: 213441.986 ms\n(7 rows)\n\n2) groupagg\n\n QUERY PLAN\n----------------------------------------------------------------------------------------------------------------------------------------------\n Limit (cost=36755617.81..36755617.81 rows=1 width=36) (actual time=180029.594..180029.595 rows=0 loops=1)\n -> GroupAggregate (cost=35214909.30..36755617.81 rows=6718533 width=36) (actual time=94017.788..179857.683 rows=6400000 loops=1)\n Group Key: lineitem.l_partkey\n -> Sort (cost=35214909.30..35694886.14 rows=191990736 width=9) (actual time=94017.750..151138.727 rows=192000551 loops=1)\n Sort Key: lineitem.l_partkey\n Sort Method: external merge Disk: 3742208kB\n -> Seq Scan on lineitem (cost=0.00..5519288.36 rows=191990736 width=9) (actual time=0.008..26831.264 rows=192000551 loops=1)\n Planning Time: 0.063 ms\n Execution Time: 180209.580 ms\n(9 rows)\n\n\nI still don't understand why the hashagg is costed so low compared to\nthe sort (only about 1/3 of it), because both cases use exactly the same\nestimates internally. cost_tuplesort ends up with\n\n npages = 937455\n nruns = 114.435396\n input_bytes = 7679629440\n log_runs = 1.0\n\nwhile cost_agg uses\n\n pages_read = 937455\n pages_written = 937455\n relation_size = 7679629440;\n\nyet we end up with much lower estimate for hashagg. It however does seem\nto me this is mostly due to non-I/O costs, considered by cost_tuplesort\nand perhaps ignored by cost_agg? In particular, most of the sort cost\ncomes from this\n\n *startup_cost = comparison_cost * tuples * LOG2(tuples);\n\nSo I'm wondering if the hashagg is not ignoring similar non-I/O costs\nfor the spilling case. In particular, the initial section computing\nstartup_cost seems to ignore that we may need to so some of the stuff\nrepeatedly - for example we'll repeat hash lookups for spilled tuples,\nand so on.\n\nThe other thing is that sort seems to be doing only about half the\nphysical I/O (as measured by iosnoop) compared to hashagg, even though\nthe estimates of pages / input_bytes are exactly the same. For hashagg\nthe iosnoop shows 5921MB reads and 7185MB writes, while sort only does\n2895MB reads and 3655MB writes. Which kinda matches the observed sizes\nof temp files in the two cases, so the input_bytes for sort seems to be\na bit overestimated.\n\n\nregards\n\n[1] https://www.postgresql.org/message-id/20200724012248.y77rpqc73agrsvb3@development\n\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Sun, 30 Aug 2020 17:03:15 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Disk-based hash aggregate's cost model" }, { "msg_contents": "On Sun, 2020-08-30 at 17:03 +0200, Tomas Vondra wrote:\n> So I'm wondering if the hashagg is not ignoring similar non-I/O costs\n> for the spilling case. In particular, the initial section computing\n> startup_cost seems to ignore that we may need to so some of the stuff\n> repeatedly - for example we'll repeat hash lookups for spilled\n> tuples,\n> and so on.\n\nTo fix that, we'd also need to change the cost of in-memory HashAgg,\nright?\n\n> The other thing is that sort seems to be doing only about half the\n> physical I/O (as measured by iosnoop) compared to hashagg, even\n> though\n> the estimates of pages / input_bytes are exactly the same. For\n> hashagg\n> the iosnoop shows 5921MB reads and 7185MB writes, while sort only\n> does\n> 2895MB reads and 3655MB writes. Which kinda matches the observed\n> sizes\n> of temp files in the two cases, so the input_bytes for sort seems to\n> be\n> a bit overestimated.\n\nHmm, interesting.\n\nHow reasonable is it to be making these kinds of changes to the cost\nmodel right now? I think your analysis is solid, but I'm worried about\nmaking more intrusive changes very late in the cycle.\n\nI had originally tried to limit the cost model changes to the new plans\nI am introducing -- that is, HashAgg plans expected to require disk.\nThat's why I came up with a rather arbitrary penalty.\n\nRegards,\n\tJeff Davis\n\n\n\n\n", "msg_date": "Mon, 31 Aug 2020 23:34:34 -0700", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: Disk-based hash aggregate's cost model" }, { "msg_contents": "On Mon, Aug 31, 2020 at 11:34:34PM -0700, Jeff Davis wrote:\n>On Sun, 2020-08-30 at 17:03 +0200, Tomas Vondra wrote:\n>> So I'm wondering if the hashagg is not ignoring similar non-I/O costs\n>> for the spilling case. In particular, the initial section computing\n>> startup_cost seems to ignore that we may need to so some of the stuff\n>> repeatedly - for example we'll repeat hash lookups for spilled\n>> tuples,\n>> and so on.\n>\n>To fix that, we'd also need to change the cost of in-memory HashAgg,\n>right?\n>\n\nWhy? I don't think we need to change costing of in-memory HashAgg. My\nassumption was we'd only tweak startup_cost for cases with spilling by\nadding something like (cpu_operator_cost * npartitions * ntuples).\n\n>> The other thing is that sort seems to be doing only about half the\n>> physical I/O (as measured by iosnoop) compared to hashagg, even\n>> though\n>> the estimates of pages / input_bytes are exactly the same. For\n>> hashagg\n>> the iosnoop shows 5921MB reads and 7185MB writes, while sort only\n>> does\n>> 2895MB reads and 3655MB writes. Which kinda matches the observed\n>> sizes\n>> of temp files in the two cases, so the input_bytes for sort seems to\n>> be\n>> a bit overestimated.\n>\n>Hmm, interesting.\n>\n\nFWIW I suspect some of this difference may be due to logical vs.\nphysical I/O. iosnoop only tracks physical I/O sent to the device, but\nmaybe we do much more logical I/O and it simply does not expire from\npage cache for the sort. It might behave differently for larger data\nset, longer query, ...\n\n>How reasonable is it to be making these kinds of changes to the cost\n>model right now? I think your analysis is solid, but I'm worried about\n>making more intrusive changes very late in the cycle.\n>\n>I had originally tried to limit the cost model changes to the new plans\n>I am introducing -- that is, HashAgg plans expected to require disk.\n>That's why I came up with a rather arbitrary penalty.\n>\n\nI don't know. I certainly understand the desire not to change things\nthis late. OTOH I'm worried that we'll end up receiving a lot of poor\nplans post release.\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, 1 Sep 2020 11:19:03 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Disk-based hash aggregate's cost model" }, { "msg_contents": "On Tue, 2020-09-01 at 11:19 +0200, Tomas Vondra wrote:\n> Why? I don't think we need to change costing of in-memory HashAgg. My\n> assumption was we'd only tweak startup_cost for cases with spilling\n> by\n> adding something like (cpu_operator_cost * npartitions * ntuples).\n\nThe code above (the in-memory case) has a clause:\n\n startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;\n\nwhich seems to account only for the hash calculation, because it's\nmultiplying by the number of grouping columns.\n\nYour calculation would also use cpu_operator_cost, but just for the\nlookup. I'm OK with that, but it's a little inconsistent to only count\nit for the tuples that spill to disk.\n\nBut why multiply by the number of partitions? Wouldn't it be the depth?\nA wide fanout will not increase the number of lookups.\n\n> FWIW I suspect some of this difference may be due to logical vs.\n> physical I/O. iosnoop only tracks physical I/O sent to the device,\n> but\n> maybe we do much more logical I/O and it simply does not expire from\n> page cache for the sort. It might behave differently for larger data\n> set, longer query, ...\n\nThat would suggest something like a penalty for HashAgg for being a\nworse IO pattern. Or do you have another suggestion?\n\n> I don't know. I certainly understand the desire not to change things\n> this late. OTOH I'm worried that we'll end up receiving a lot of poor\n> plans post release.\n\nI was reacting mostly to changing the cost of Sort. Do you think\nchanges to Sort are required or did I misunderstand?\n\nRegards,\n\tJeff Davis\n\n\n\n\n", "msg_date": "Tue, 01 Sep 2020 12:58:59 -0700", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: Disk-based hash aggregate's cost model" }, { "msg_contents": "On Tue, Sep 01, 2020 at 12:58:59PM -0700, Jeff Davis wrote:\n>On Tue, 2020-09-01 at 11:19 +0200, Tomas Vondra wrote:\n>> Why? I don't think we need to change costing of in-memory HashAgg. My\n>> assumption was we'd only tweak startup_cost for cases with spilling\n>> by\n>> adding something like (cpu_operator_cost * npartitions * ntuples).\n>\n>The code above (the in-memory case) has a clause:\n>\n> startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;\n>\n>which seems to account only for the hash calculation, because it's\n>multiplying by the number of grouping columns.\n>\n>Your calculation would also use cpu_operator_cost, but just for the\n>lookup. I'm OK with that, but it's a little inconsistent to only count\n>it for the tuples that spill to disk.\n>\n>But why multiply by the number of partitions? Wouldn't it be the depth?\n>A wide fanout will not increase the number of lookups.\n>\n\nYeah, I think you're right it should be depth, not number of partitions.\n\nFWIW I don't know if this is enough to \"fix\" the costing, it's just\nsomething I noticed while looking at the code.\n\n>> FWIW I suspect some of this difference may be due to logical vs.\n>> physical I/O. iosnoop only tracks physical I/O sent to the device,\n>> but\n>> maybe we do much more logical I/O and it simply does not expire from\n>> page cache for the sort. It might behave differently for larger data\n>> set, longer query, ...\n>\n>That would suggest something like a penalty for HashAgg for being a\n>worse IO pattern. Or do you have another suggestion?\n>\n\nPossibly, yes. I think it'd be good to measure logical I/O (e.g. by\nadding some instrumentation to LogicalTapeSet) to see if this hypothesis\nis actually true.\n\nFWIW any thoughts about the different in temp size compared to\nCP_SMALL_TLIST?\n\n>> I don't know. I certainly understand the desire not to change things\n>> this late. OTOH I'm worried that we'll end up receiving a lot of poor\n>> plans post release.\n>\n>I was reacting mostly to changing the cost of Sort. Do you think\n>changes to Sort are required or did I misunderstand?\n>\n\nNot sure I'm following. I don't think anyone proposed changing costing\nfor Sort. Or did I miss something?\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, 1 Sep 2020 23:19:30 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Disk-based hash aggregate's cost model" }, { "msg_contents": "On Tue, Sep 1, 2020 at 2:19 AM Tomas Vondra\n<tomas.vondra@2ndquadrant.com> wrote:\n> FWIW I suspect some of this difference may be due to logical vs.\n> physical I/O. iosnoop only tracks physical I/O sent to the device, but\n> maybe we do much more logical I/O and it simply does not expire from\n> page cache for the sort. It might behave differently for larger data\n> set, longer query, ...\n\nThere is also the fact that the LogicalTapeSetBlocks() instrumentation\nis known to have problems that we still need to fix:\n\nhttps://www.postgresql.org/message-id/CAH2-Wzn5PCBLUrrds=hD439LtWP+PD7ekRTd=8LdtqJ+KO5D1Q@mail.gmail.com\n\nI'm not suggesting that this is a significant factor here. But I can't\nrule it out just yet either.\n\n> I don't know. I certainly understand the desire not to change things\n> this late. OTOH I'm worried that we'll end up receiving a lot of poor\n> plans post release.\n\nI think that this needs to get fixed before release.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Tue, 1 Sep 2020 14:48:07 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: Disk-based hash aggregate's cost model" }, { "msg_contents": "On Sun, 2020-08-30 at 17:03 +0200, Tomas Vondra wrote:\n> So I'm wondering if the hashagg is not ignoring similar non-I/O costs\n> for the spilling case. In particular, the initial section computing\n> startup_cost seems to ignore that we may need to so some of the stuff\n> repeatedly - for example we'll repeat hash lookups for spilled\n> tuples,\n> and so on.\n\nI tried to analyze this using a slightly different approach: cost units\nper second of runtime. Obviously this will vary based on the machine,\nbut it's interesting anyway.\n\nAll of the following fit in system memory. Schema, data, and queries\nare at the end of this email.\n\nA low value of cost-units/second-runtime means \"more likely to be\nchosen incorrectly\" and a high value means \"more likely to be missed\nincorrectly\".\n\nPlan | work_mem | 10M | 100M INT4 | 100M | 10M\n | | INT4 | (10M groups) | INT4 | TEXT\n--------+----------+------+--------------+------+-----\nHashAgg | 4MB | 88 | 63 | 82 | 78\nHashAgg | 1TB | 41 | 37 | 33 | 38\nSort | 4MB | 182 | 188 | 174 | 37\nSort | 1TB | 184 | 231 | 189 | 30\n\n\nSort is consistent for a given datatype, but it seems that the\ncomparison cost is far from proportionate between data types.\n\nHashAgg is consistent between the data types, but the disk costs play a\nlarger role (in this case, there is no actual disk access to worry\nabout, because it fits in system memory).\n\nAt least for these simple queries, Sort is punished unfairly for INT4,\nbut gets an unfair boost for TEXT.\n\nIt seems that we should make a change here, but to be conservative for\n13, we should limit changes to the new plans, which are the first line\n(HashAgg that spills).\n\nThe attached patch makes two adjustments: a 2X disk penalty for\nHashAgg, and I also add:\n\n spill_cost = depth * input_tuples * 2.0 * cpu_tuple_cost\n\nThe new results:\n\nPlan | work_mem | 10M | 100M INT4 | 100M | 10M\n | | INT4 | (10M groups) | INT4 | TEXT\n--------+----------+------+--------------+------+-----\nHashAgg | 4MB | 192 | 131 | 178 | 166\n\n\nThat's much more comparable to Sort for INT4, but makes the gap wider\nfor TEXT. Fortunately, at least for my simple queries, it just barely\navoids a plan change to Sort for the TEXT case (which is nearly 5X\nslower than HashAgg).\n\nI think this approach is reasonable for 13: it only changes the costing\nfor HashAgg plans that are expected to spill, it's fairly conservative\nso we will not get lots of new bad plans, and it still seems to use\nHashAgg for cases where it clearly should.\n\nNote: in-memory HashAgg is still unfairly favored over Sort, at least\nfor these cases.\n\nRegards,\n\tJeff Davis\n\n\ncreate table t10m(i int);\ninsert into t10m select (random()*1000000000)::int from\ngenerate_series(1,10000000);\nexplain analyze select distinct i from t10m;\n\ncreate table t100m(i int);\ninsert into t100m select (random()*2000000000)::int from\ngenerate_series(1,100000000);\nexplain analyze select distinct i from t100m;\n\n-- 100m tuples, 10m groups, 10tuples/group\ncreate table t100m_10(i int);\ninsert into t100m_10 select (random()*10000000)::int from\ngenerate_series(1,100000000);\nexplain analyze select distinct i from t100m_10;\n\ncreate table text10m(t text collate \"C.UTF-8\", i int, n numeric);\ninsert into text10m select s.g::text, s.g, s.g::numeric from (select\n(random()*1000000000)::int as g from generate_series(1,10000000)) s;\nexplain analyze select distinct t from text10m;", "msg_date": "Wed, 02 Sep 2020 17:18:23 -0700", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: Disk-based hash aggregate's cost model" }, { "msg_contents": "On Wed, Sep 2, 2020 at 5:18 PM Jeff Davis <pgsql@j-davis.com> wrote:\n> create table text10m(t text collate \"C.UTF-8\", i int, n numeric);\n> insert into text10m select s.g::text, s.g, s.g::numeric from (select\n> (random()*1000000000)::int as g from generate_series(1,10000000)) s;\n> explain analyze select distinct t from text10m;\n\nNote that you won't get what Postgres considers to be the C collation\nunless you specify \"collate C\" -- \"C.UTF-8\" is the C collation exposed\nby glibc. The difference matters a lot, because only the former can\nuse abbreviated keys (unless you manually #define TRUST_STRXFRM). And\neven without abbreviated keys it's probably still significantly faster\nfor other reasons.\n\nThis doesn't undermine your point, because we don't take the\ndifference into account in cost_sort() -- even though abbreviated keys\nwill regularly make text sorts 2x-3x faster. My point is only that it\nwould be more accurate to say that the costing unfairly boosts sorts\non collated texts specifically. Though maybe not when an ICU collation\nis used (since abbreviated keys will be enabled generally).\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Wed, 2 Sep 2020 17:35:13 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: Disk-based hash aggregate's cost model" }, { "msg_contents": "On Wed, 2020-09-02 at 17:35 -0700, Peter Geoghegan wrote:\n> On Wed, Sep 2, 2020 at 5:18 PM Jeff Davis <pgsql@j-davis.com> wrote:\n> > create table text10m(t text collate \"C.UTF-8\", i int, n numeric);\n> > insert into text10m select s.g::text, s.g, s.g::numeric from\n> > (select\n> > (random()*1000000000)::int as g from generate_series(1,10000000))\n> > s;\n> > explain analyze select distinct t from text10m;\n> \n> Note that you won't get what Postgres considers to be the C collation\n> unless you specify \"collate C\" -- \"C.UTF-8\" is the C collation\n> exposed\n> by glibc. The difference matters a lot, because only the former can\n> use abbreviated keys (unless you manually #define TRUST_STRXFRM). And\n> even without abbreviated keys it's probably still significantly\n> faster\n> for other reasons.\n\nThank you. I reran with:\n\n create table text10m2(t text collate \"C\", i int, n numeric);\n -- same data, same queries\n\nAnd the new table is:\n\nPlan | work | 10M | 100M INT4 | 100M | 10M | 10M\n | mem | INT4 | 10M grps | INT4 | TEXT | TEXTC\n---------+------+------+-----------+------+------+------\nHashAgg | 4MB | 88 | 63 | 82 | 78 | 80\nHashAgg | 1TB | 41 | 37 | 33 | 38 | 43\nSort | 4MB | 182 | 188 | 174 | 37 | 146\nSort | 1TB | 184 | 231 | 189 | 30 | 149\nHashAgg* | 4MB | 192 | 131 | 178 | 166 | 176\n\n*: patched\n\nFor the 'COLLATE \"C\"' case, the costs still come out the almost the\nsame between HashAgg and Sort, but the runtimes are much closer. So\neven if it did flip the plan from HashAgg to Sort, it goes from 9.5s\n(HashAgg) to 12s (Sort), which is not so bad.\n\nSo the patched version looks good to me at this point. It accounts for\nTomas's observations about IO:\n\n \"The other thing is that sort seems to be doing only about half the\nphysical I/O (as measured by iosnoop) compared to hashagg, even though\nthe estimates of pages / input_bytes are exactly the same.\"\n\nby penalizing HashAgg disk costs by 2X.\n\nThe patch also accounts for his other observation about missing CPU\ncosts by costing the spilling. Tomas framed the CPU costs as the cost\nof the extra lookups, but the extra lookups are only in the cases where\nit misses in the hash table and needs to spill. So I think it's\nreasonable to consider the extra lookups as a part of the spill cost.\n\nThe remaining problems are:\n\n* comparison costs for Sort should be adjusted to make them relatively\nconsistent between data types\n* in-memory HashAgg is unfairly favored in a lot of cases\n\nI don't think either of those problems need to be (or should be) fixed\nin 13, but we can revisit in 14 if there are reports of bad plans.\n\nRegards,\n\tJeff Davis\n\n\n\n\n", "msg_date": "Thu, 03 Sep 2020 09:38:06 -0700", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: Disk-based hash aggregate's cost model" }, { "msg_contents": "On Tue, 2020-09-01 at 23:19 +0200, Tomas Vondra wrote:\n> FWIW any thoughts about the different in temp size compared to\n> CP_SMALL_TLIST?\n\nAre you referring to results from a while ago? In this thread I don't\nsee what you're referring to.\n\nI tried in a simple case on REL_13_STABLE, with and without the\nCP_SMALL_TLIST change, and I saw only a tiny difference. Do you have a\ncurrent case that shows a larger difference?\n\nThe only thing I can think of that might change is the size of the null\nbitmap or how fields are aligned.\n\nRegards,\n\tJeff Davis\n\n\n\n\n", "msg_date": "Thu, 03 Sep 2020 17:53:43 -0700", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: Disk-based hash aggregate's cost model" }, { "msg_contents": "On Thu, Sep 03, 2020 at 05:53:43PM -0700, Jeff Davis wrote:\n>On Tue, 2020-09-01 at 23:19 +0200, Tomas Vondra wrote:\n>> FWIW any thoughts about the different in temp size compared to\n>> CP_SMALL_TLIST?\n>\n>Are you referring to results from a while ago? In this thread I don't\n>see what you're referring to.\n>\n>I tried in a simple case on REL_13_STABLE, with and without the\n>CP_SMALL_TLIST change, and I saw only a tiny difference. Do you have a\n>current case that shows a larger difference?\n>\n\nI'm referring to the last charts in the message from July 27, comparing\nbehavior with CP_SMALL_TLIST fix vs. master (which reverted/replaced the\nCP_SMALL_TLIST bit).\n\nThose charts show that the CP_SMALL_TLIST resulted in smaller temp files\n(per EXPLAIN ANALYZE the difference is ~25%) and also lower query\ndurations (also in the ~25% range).\n\nI can repeat those tests, if needed.\n\n[1] https://www.postgresql.org/message-id/20200724012248.y77rpqc73agrsvb3@development\n\n>The only thing I can think of that might change is the size of the null\n>bitmap or how fields are aligned.\n>\n\nMaybe. Not sure.\n\n\nregards\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 4 Sep 2020 14:56:40 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Disk-based hash aggregate's cost model" }, { "msg_contents": "On Fri, 2020-09-04 at 14:56 +0200, Tomas Vondra wrote:\n> Those charts show that the CP_SMALL_TLIST resulted in smaller temp\n> files\n> (per EXPLAIN ANALYZE the difference is ~25%) and also lower query\n> durations (also in the ~25% range).\n\nI was able to reproduce the problem, thank you.\n\nOnly two attributes are needed, so the CP_SMALL_TLIST projected schema\nonly needs a single-byte null bitmap.\n\nBut if just setting the attributes to NULL rather than projecting them,\nthe null bitmap size is based on all 16 attributes, bumping the bitmap\nsize to two bytes.\n\nMAXALIGN(23 + 1) = 24\nMAXALIGN(23 + 2) = 32\n\nI think that explains it. It's not ideal, but projection has a cost as\nwell, so I don't think we necessarily need to do something here.\n\nIf we are motivated to improve this in v14, we could potentially have a\ndifferent schema for spilled tuples, and perform real projection at\nspill time. But I don't know if that's worth the extra complexity.\n\nRegards,\n\tJeff Davis\n\n\n\n\n", "msg_date": "Fri, 04 Sep 2020 11:31:36 -0700", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: Disk-based hash aggregate's cost model" }, { "msg_contents": "On Fri, Sep 04, 2020 at 11:31:36AM -0700, Jeff Davis wrote:\n>On Fri, 2020-09-04 at 14:56 +0200, Tomas Vondra wrote:\n>> Those charts show that the CP_SMALL_TLIST resulted in smaller temp\n>> files\n>> (per EXPLAIN ANALYZE the difference is ~25%) and also lower query\n>> durations (also in the ~25% range).\n>\n>I was able to reproduce the problem, thank you.\n>\n>Only two attributes are needed, so the CP_SMALL_TLIST projected schema\n>only needs a single-byte null bitmap.\n>\n>But if just setting the attributes to NULL rather than projecting them,\n>the null bitmap size is based on all 16 attributes, bumping the bitmap\n>size to two bytes.\n>\n>MAXALIGN(23 + 1) = 24\n>MAXALIGN(23 + 2) = 32\n>\n>I think that explains it. It's not ideal, but projection has a cost as\n>well, so I don't think we necessarily need to do something here.\n>\n>If we are motivated to improve this in v14, we could potentially have a\n>different schema for spilled tuples, and perform real projection at\n>spill time. But I don't know if that's worth the extra complexity.\n>\n\nThanks for the investigation and explanation.\n\nWouldn't it be enough to just use a slot with smaller tuple descriptor?\nAll we'd need to do is creating the descriptor in ExecInitAgg after\ncalling find_hash_columns, and using it for rslot/wslot, and then\n\"mapping\" the attributes in hashagg_spill_tuple (which already almost\ndoes that, to the extra cost should be 0) and when reading the spilled\ntuples. So I'm not quite buying the argument that this would make\nmeasurable difference ...\n\nThat being said, I won't insist on fixing this in v13 - at least we know\nwhat the issue is and we can fix it later. The costing seems like a more\nserious open item.\n\nOTOH I don't think this example is particularly extreme, and I wouldn't\nbe surprised if we se even worse examples in practice - tables tend to\nbe quite wide and aggregation of just a few columns seems likely.\n\n\nregards\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 4 Sep 2020 21:01:37 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Disk-based hash aggregate's cost model" }, { "msg_contents": "On Fri, 2020-09-04 at 21:01 +0200, Tomas Vondra wrote:\n> Wouldn't it be enough to just use a slot with smaller tuple\n> descriptor?\n> All we'd need to do is creating the descriptor in ExecInitAgg after\n> calling find_hash_columns, and using it for rslot/wslot, and then\n> \"mapping\" the attributes in hashagg_spill_tuple (which already almost\n> does that, to the extra cost should be 0) and when reading the\n> spilled\n> tuples.\n\nThat's a good point, it's probably not much code to make it work.\n\n> So I'm not quite buying the argument that this would make\n> measurable difference ...\n\nI meant \"projection of all input tuples\" (i.e. CP_SMALL_TLIST) has a\ncost. If we project only at spill time, it should be fine.\n\nRegards,\n\tJeff Davis\n\n\n\n\n", "msg_date": "Fri, 04 Sep 2020 12:33:24 -0700", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: Disk-based hash aggregate's cost model" }, { "msg_contents": "Hi,\n\nI've tested the costing changes on the simplified TPC-H query, on two\ndifferent machines, and it seems like a clear improvement.\n\nThis is using the same cost/duration measure, which I think is pretty\nneat way to look at this. Sure, it's imperfect (depends on which cost\nand durations you actually take etc.), but it makes the comparisons\neasier and for simple queries it does not matter that much.\n\nThe costing clearly depends on parameters like random_page_cost and how\nit matches the hardware, but for the machine with SSD and default\nrandom_page_cost the effect looks like this:\n\n work_mem sort master patched\n ---------------------------------------\n 1MB 249 95 215\n 2MB 256 89 187\n 4MB 233 90 192\n 8MB 227 70 124\n 16MB 245 67 118\n 32MB 261 63 111\n 64MB 256 59 104\n 256MB 266 55 102\n\nand with random_page_cost reduced to 1.5 it looks like this:\n\n work_mem sort master patched\n ------------------------------------------\n 1MB 221 63 150\n 2MB 227 64 133\n 4MB 214 65 137\n 8MB 214 57 95\n 16MB 232 53 90\n 32MB 247 50 85\n 64MB 249 47 80\n 256MB 258 46 77\n\nAnd on a machine with SATA RAID storage it looks like this:\n\n work_mem sort master patched\n -----------------------------------------\n 1MB 102 41 94\n 2MB 101 34 77\n 4MB 99 35 78\n 8MB 98 35 79\n 16MB 98 25 50\n 32MB 106 26 51\n 64MB 106 26 51\n 256MB 105 29 50\n\nSo yeah, the patched costing is much closer to sort (from the point of\nthis cost/duration metric), although for higher work_mem values there's\nstill a clear gap where the hashing seems to be under-costed by a factor\nof ~2 or more.\n\nI think this is simply showing that sort may the effect of increasing\nwork_mem is much more pronounced for sort/groupagg compared to hashagg.\nFor example on the SDD machine the duration changes like this:\n\n work_mem hashagg groupagg\n ---------------------------------\n 1MB 217 201\n 2MB 178 195\n 4MB 176 186\n 8MB 160 176\n 16MB 168 163\n 32MB 180 153\n 64MB 189 143\n 256MB 204 138\n\nand the SATA RAID storage seems to behave in a similar way (although the\ndifference is smaller).\n\nSo in general I think this costing change is reasonable. It might not go\nfar enough, but it certainly makes it probably makes it easier to tweak\nthe rest by changing random_page_cost etc. Not sure if we need/should\ntweak the costing to reduce the effect of work_mem (on hashagg).\n\nregards\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Sun, 6 Sep 2020 23:21:12 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Disk-based hash aggregate's cost model" }, { "msg_contents": "On Sun, 2020-09-06 at 23:21 +0200, Tomas Vondra wrote:\n> I've tested the costing changes on the simplified TPC-H query, on two\n> different machines, and it seems like a clear improvement.\n\nThank you. Committed.\n\n> So yeah, the patched costing is much closer to sort (from the point\n> of\n> this cost/duration metric), although for higher work_mem values\n> there's\n> still a clear gap where the hashing seems to be under-costed by a\n> factor\n> of ~2 or more.\n\nThere seems to be a cliff right after 4MB. Perhaps lookup costs on a\nlarger hash table?\n\nRegards,\n\tJeff Davis\n\n\n\n", "msg_date": "Mon, 07 Sep 2020 13:55:28 -0700", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: Disk-based hash aggregate's cost model" }, { "msg_contents": "On Mon, Sep 07, 2020 at 01:55:28PM -0700, Jeff Davis wrote:\n>On Sun, 2020-09-06 at 23:21 +0200, Tomas Vondra wrote:\n>> I've tested the costing changes on the simplified TPC-H query, on two\n>> different machines, and it seems like a clear improvement.\n>\n>Thank you. Committed.\n>\n>> So yeah, the patched costing is much closer to sort (from the point\n>> of\n>> this cost/duration metric), although for higher work_mem values\n>> there's\n>> still a clear gap where the hashing seems to be under-costed by a\n>> factor\n>> of ~2 or more.\n>\n>There seems to be a cliff right after 4MB. Perhaps lookup costs on a\n>larger hash table?\n>\n\nI assume you mean higher costs due to hash table outgrowing some sort of\nCPU cache (L2/L3), right? Good guess - the CPU has ~6MB cache, but no.\nThis seems to be merely due to costing, because the raw cost/duration\nlooks like this:\n\n work_mem cost duration\n ---------------------------------\n 1MB 20627403 216861\n 2MB 15939722 178237\n 4MB 15939722 176296\n 8MB 11252041 160479\n 16MB 11252041 168304\n 32MB 11252041 179567\n 64MB 11252041 189410\n 256MB 11252041 204206\n\nThis is unpatched master, with the costing patch it looks similar except\nthat the cost is about 2x higher. On the SATA RAID machine, it looks\nlike this:\n\n work_mem cost duration\n -----------------------------------\n 1MB 108358461 1147269\n 2MB 77381688 1004895\n 4MB 77381688 994853\n 8MB 77381688 980071\n 16MB 46404915 930511\n 32MB 46404915 902167\n 64MB 46404915 908757\n 256MB 46404915 926862\n\nSo roughly the same - the cost drops to less than 50%, but the duration\nreally does not. This is what I referred to when I said \"Not sure if we\nneed/should tweak the costing to reduce the effect of work_mem (on\nhashagg).\"\n\nFor sort this seems to behave a bit more nicely - the cost and duration\n(with increasing work_mem) are correlated quite well, I think.\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, 8 Sep 2020 16:06:58 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Disk-based hash aggregate's cost model" } ]
[ { "msg_contents": "Greetings,\n\nThere's no shortage of requests and responses regarding how to have a\n'read all of the data' role in PG, with various hacks involving \"GRANT\nALL\" and \"ALTER DEFAULT PRIVILEGES\" to \"solve\" this, neither of which\nreally works long term (\"GRANT ALL\" is one-time, and \"ALTER DEFAULT\"\nonly helps for the roles that exist today).\n\nNow that we have the default role system, we can provide a proper\nsolution to this oft-requested capability.\n\nThis patch adds a default role to meet specifically that use-case, in\nthe long-term, by explicitly allowing SELECT rights on all relations,\nand USAGE rights on all schemas, for roles who are members of the new\n'pg_read_all_data' role.\n\nNo effort is made to prevent a user who has this role from writing data-\nthat's up to the admin, but this will allow someone to use pg_dump or\npg_dumpall in a much more reliable manner to make sure that the entire\ndatabase is able to be exported for the purpose of backups, upgrades, or\nother common use-cases, without having to have that same user be a PG\nsuperuser.\n\nThis role is given the Bypass RLS right, though to use it effectively, a\nuser would need to pass '--role=pg_read_all_data' to pg_dump/pg_dumpall,\nsince role attributes are not checked as part of role membership.\n\nThoughts?\n\nWill add to the September CF.\n\nThanks,\n\nStephen", "msg_date": "Thu, 27 Aug 2020 20:30:23 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": true, "msg_subject": "New default role- 'pg_read_all_data'" }, { "msg_contents": "On Thu, Aug 27, 2020 at 5:30 PM Stephen Frost <sfrost@snowman.net> wrote:\n\n> Greetings,\n>\n> There's no shortage of requests and responses regarding how to have a\n> 'read all of the data' role in PG, with various hacks involving \"GRANT\n> ALL\" and \"ALTER DEFAULT PRIVILEGES\" to \"solve\" this, neither of which\n> really works long term (\"GRANT ALL\" is one-time, and \"ALTER DEFAULT\"\n> only helps for the roles that exist today).\n>\n> Now that we have the default role system, we can provide a proper\n> solution to this oft-requested capability.\n>\n> This patch adds a default role to meet specifically that use-case, in\n> the long-term, by explicitly allowing SELECT rights on all relations,\n> and USAGE rights on all schemas, for roles who are members of the new\n> 'pg_read_all_data' role.\n>\n> No effort is made to prevent a user who has this role from writing data-\n> that's up to the admin, but this will allow someone to use pg_dump or\n> pg_dumpall in a much more reliable manner to make sure that the entire\n> database is able to be exported for the purpose of backups, upgrades, or\n> other common use-cases, without having to have that same user be a PG\n> superuser.\n>\n> This role is given the Bypass RLS right, though to use it effectively, a\n> user would need to pass '--role=pg_read_all_data' to pg_dump/pg_dumpall,\n> since role attributes are not checked as part of role membership.\n>\n>\nThis will be much appreciated from an app developers perspective. It makes\nlife so much easier to \"do the right thing\" in terms of giving read only\nwebapps the right permissions.\n\nOn Thu, Aug 27, 2020 at 5:30 PM Stephen Frost <sfrost@snowman.net> wrote:Greetings,\n\nThere's no shortage of requests and responses regarding how to have a\n'read all of the data' role in PG, with various hacks involving \"GRANT\nALL\" and \"ALTER DEFAULT PRIVILEGES\" to \"solve\" this, neither of which\nreally works long term (\"GRANT ALL\" is one-time, and \"ALTER DEFAULT\"\nonly helps for the roles that exist today).\n\nNow that we have the default role system, we can provide a proper\nsolution to this oft-requested capability.\n\nThis patch adds a default role to meet specifically that use-case, in\nthe long-term, by explicitly allowing SELECT rights on all relations,\nand USAGE rights on all schemas, for roles who are members of the new\n'pg_read_all_data' role.\n\nNo effort is made to prevent a user who has this role from writing data-\nthat's up to the admin, but this will allow someone to use pg_dump or\npg_dumpall in a much more reliable manner to make sure that the entire\ndatabase is able to be exported for the purpose of backups, upgrades, or\nother common use-cases, without having to have that same user be a PG\nsuperuser.\n\nThis role is given the Bypass RLS right, though to use it effectively, a\nuser would need to pass '--role=pg_read_all_data' to pg_dump/pg_dumpall,\nsince role attributes are not checked as part of role membership.\nThis will be much appreciated from an app developers perspective. It makes life so much easier to \"do the right thing\" in terms of giving read only webapps the right permissions.", "msg_date": "Thu, 27 Aug 2020 18:17:58 -0700", "msg_from": "Steven Pousty <steve.pousty@gmail.com>", "msg_from_op": false, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "On Fri, Aug 28, 2020 at 2:30 AM Stephen Frost <sfrost@snowman.net> wrote:\n\n> Greetings,\n>\n> There's no shortage of requests and responses regarding how to have a\n> 'read all of the data' role in PG, with various hacks involving \"GRANT\n> ALL\" and \"ALTER DEFAULT PRIVILEGES\" to \"solve\" this, neither of which\n> really works long term (\"GRANT ALL\" is one-time, and \"ALTER DEFAULT\"\n> only helps for the roles that exist today).\n>\n> Now that we have the default role system, we can provide a proper\n> solution to this oft-requested capability.\n>\n> This patch adds a default role to meet specifically that use-case, in\n> the long-term, by explicitly allowing SELECT rights on all relations,\n> and USAGE rights on all schemas, for roles who are members of the new\n> 'pg_read_all_data' role.\n>\n> No effort is made to prevent a user who has this role from writing data-\n> that's up to the admin, but this will allow someone to use pg_dump or\n> pg_dumpall in a much more reliable manner to make sure that the entire\n> database is able to be exported for the purpose of backups, upgrades, or\n> other common use-cases, without having to have that same user be a PG\n> superuser.\n>\n> This role is given the Bypass RLS right, though to use it effectively, a\n> user would need to pass '--role=pg_read_all_data' to pg_dump/pg_dumpall,\n> since role attributes are not checked as part of role membership.\n>\n> Thoughts?\n>\n\nWithout having actually looked at the code, definite +1 for this feature.\nIt's much requested...\n\nBut, should we also have a pg_write_all_data to go along with 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 Fri, Aug 28, 2020 at 2:30 AM Stephen Frost <sfrost@snowman.net> wrote:Greetings,\n\nThere's no shortage of requests and responses regarding how to have a\n'read all of the data' role in PG, with various hacks involving \"GRANT\nALL\" and \"ALTER DEFAULT PRIVILEGES\" to \"solve\" this, neither of which\nreally works long term (\"GRANT ALL\" is one-time, and \"ALTER DEFAULT\"\nonly helps for the roles that exist today).\n\nNow that we have the default role system, we can provide a proper\nsolution to this oft-requested capability.\n\nThis patch adds a default role to meet specifically that use-case, in\nthe long-term, by explicitly allowing SELECT rights on all relations,\nand USAGE rights on all schemas, for roles who are members of the new\n'pg_read_all_data' role.\n\nNo effort is made to prevent a user who has this role from writing data-\nthat's up to the admin, but this will allow someone to use pg_dump or\npg_dumpall in a much more reliable manner to make sure that the entire\ndatabase is able to be exported for the purpose of backups, upgrades, or\nother common use-cases, without having to have that same user be a PG\nsuperuser.\n\nThis role is given the Bypass RLS right, though to use it effectively, a\nuser would need to pass '--role=pg_read_all_data' to pg_dump/pg_dumpall,\nsince role attributes are not checked as part of role membership.\n\nThoughts?Without having actually looked at the code, definite +1 for this feature. It's much requested...But, should we also have a pg_write_all_data to go along with it? --  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Fri, 28 Aug 2020 12:13:29 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "Thank you for the patch.\r\n\r\nMy high level review comment:\r\nThe patch seems to be implementing a useful and requested feature.\r\nThe patch applies cleanly and passes the basic regress tests. Also the commitfest bot is happy.\r\n\r\nA first pass at the code, has not revealed any worthwhile comments.\r\nPlease allow me for a second and more thorough pass. The commitfest has hardly started after all.\r\n\r\nAlso allow me a series of genuine questions: \r\n\r\nWhat would the behaviour be with REVOKE?\r\nIn a sequence similar to:\r\nGRANT ALL ON ...\r\nREVOKE pg_read_all_data FROM ...\r\nWhat privileges would the user be left with? Would it be possible to end up in the same privilege only with a GRANT command?\r\nDoes the above scenario even make sense?\r\n\r\nRegards,", "msg_date": "Fri, 28 Aug 2020 12:16:36 +0000", "msg_from": "Georgios Kokolatos <gkokolatos@protonmail.com>", "msg_from_op": false, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "Greetings,\n\n* Magnus Hagander (magnus@hagander.net) wrote:\n> Without having actually looked at the code, definite +1 for this feature.\n> It's much requested...\n\nThanks.\n\n> But, should we also have a pg_write_all_data to go along with it?\n\nPerhaps, but could certainly be a different patch, and it'd need to be\nbetter defined, it seems to me... read_all is pretty straight-forward\n(the general goal being \"make pg_dumpall/pg_dump work\"), what would\nwrite mean? INSERT? DELETE? TRUNCATE? ALTER TABLE? System catalogs?\n\nDoesn't seem like you could just declare it to be 'allow pg_restore'\neither, as that might include creating untrusted functions, et al.\n\nThanks,\n\nStephen", "msg_date": "Fri, 28 Aug 2020 08:38:48 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": true, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "Greetings,\n\n* Georgios Kokolatos (gkokolatos@protonmail.com) wrote:\n> The patch seems to be implementing a useful and requested feature.\n> The patch applies cleanly and passes the basic regress tests. Also the commitfest bot is happy.\n> \n> A first pass at the code, has not revealed any worthwhile comments.\n> Please allow me for a second and more thorough pass. The commitfest has hardly started after all.\n\nGreat, thanks!\n\n> Also allow me a series of genuine questions: \n> \n> What would the behaviour be with REVOKE?\n> In a sequence similar to:\n> GRANT ALL ON ...\n\nGRANT ALL would be independently GRANT'ing rights to some role and\ntherefore unrelated.\n\n> REVOKE pg_read_all_data FROM ...\n\nThis would simply REVOKE that role from the user. Privileges\nindependently GRANT'd directly to the user wouldn't be affected. Nor\nwould other role membership.\n\n> What privileges would the user be left with? Would it be possible to end up in the same privilege only with a GRANT command?\n\nI'm not sure what's being asked here.\n\n> Does the above scenario even make sense?\n\nI definitely believe it makes sense for a given role/user to be a member\nof pg_read_all_data and to be a member of other roles, or to have other\nprivileges GRANT'd directly to them.\n\nThanks,\n\nStephen", "msg_date": "Fri, 28 Aug 2020 08:43:03 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": true, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "On Fri, Aug 28, 2020 at 2:38 PM Stephen Frost <sfrost@snowman.net> wrote:\n\n> Greetings,\n>\n> * Magnus Hagander (magnus@hagander.net) wrote:\n> > Without having actually looked at the code, definite +1 for this feature.\n> > It's much requested...\n>\n> Thanks.\n>\n> > But, should we also have a pg_write_all_data to go along with it?\n>\n> Perhaps, but could certainly be a different patch, and it'd need to be\n> better defined, it seems to me... read_all is pretty straight-forward\n> (the general goal being \"make pg_dumpall/pg_dump work\"), what would\n> write mean? INSERT? DELETE? TRUNCATE? ALTER TABLE? System catalogs?\n>\n\nWell, it's pg_write_all_*data*, so it certainly wouldn't be alter table or\nsystem catalogs.\n\nI'd say insert/update/delete yes.\n\nTRUNCATE is always an outlier.Given it's generally classified as DDL, I\nwouldn't include it.\n\n\nDoesn't seem like you could just declare it to be 'allow pg_restore'\n> either, as that might include creating untrusted functions, et al.\n>\n\nNo definitely not. That wouldn't be the usecase at all :)\n\n(and fwiw to me the main use case for read_all_data also isn't pg_dump,\nbecause most people using pg_dump are already db owner or higher in my\nexperience. But it is nice that it helps with that too)\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 28, 2020 at 2:38 PM Stephen Frost <sfrost@snowman.net> wrote:Greetings,\n\n* Magnus Hagander (magnus@hagander.net) wrote:\n> Without having actually looked at the code, definite +1 for this feature.\n> It's much requested...\n\nThanks.\n\n> But, should we also have a pg_write_all_data to go along with it?\n\nPerhaps, but could certainly be a different patch, and it'd need to be\nbetter defined, it seems to me...  read_all is pretty straight-forward\n(the general goal being \"make pg_dumpall/pg_dump work\"), what would\nwrite mean?  INSERT?  DELETE?  TRUNCATE?  ALTER TABLE?  System catalogs?Well, it's pg_write_all_*data*, so it certainly wouldn't be alter table or system catalogs.I'd say insert/update/delete yes.TRUNCATE is always an outlier.Given it's generally classified as DDL, I wouldn't include it.\nDoesn't seem like you could just declare it to be 'allow pg_restore'\neither, as that might include creating untrusted functions, et al.No definitely not. That wouldn't be the usecase at all :)(and fwiw to me the main use case for read_all_data also isn't pg_dump, because most people using pg_dump are already db owner or higher in my experience. But it is nice that it helps with that too)--  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Fri, 28 Aug 2020 14:50:25 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "On Fri, 28 Aug 2020 at 08:43, Stephen Frost <sfrost@snowman.net> wrote:\n\n\n> This would simply REVOKE that role from the user. Privileges\n> independently GRANT'd directly to the user wouldn't be affected. Nor\n> would other role membership.\n>\n> > What privileges would the user be left with? Would it be possible to end\n> up in the same privilege only with a GRANT command?\n>\n\nWhat about:\n\nREVOKE SELECT ON [table] FROM pg_read_all_data;\n\nI guess what I’m really asking is whether pg_read_all_data is automatically\ngranted SELECT on all newly-created relations, or if the permission\nchecking system always returns TRUE when asked if pg_read_all_data can\nselect from a relation? I’m guessing it’s the latter so that it would be\nineffective to revoke select privilege as I think this is more useful, but\nI’d like to be sure and the documentation should be explicit on this point.\n\nOn Fri, 28 Aug 2020 at 08:43, Stephen Frost <sfrost@snowman.net> wrote: \nThis would simply REVOKE that role from the user.  Privileges\nindependently GRANT'd directly to the user wouldn't be affected.  Nor\nwould other role membership.\n\n> What privileges would the user be left with? Would it be possible to end up in the same privilege only with a GRANT command?What about:REVOKE SELECT ON [table] FROM pg_read_all_data;I guess what I’m really asking is whether pg_read_all_data is automatically granted SELECT on all newly-created relations, or if the permission checking system always returns TRUE when asked if pg_read_all_data can select from a relation? I’m guessing it’s the latter so that it would be ineffective to revoke select privilege as I think this is more useful, but I’d like to be sure and the documentation should be explicit on this point.", "msg_date": "Fri, 28 Aug 2020 08:51:06 -0400", "msg_from": "Isaac Morland <isaac.morland@gmail.com>", "msg_from_op": false, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "On Fri, Aug 28, 2020 at 2:43 PM Stephen Frost <sfrost@snowman.net> wrote:\n\n> Greetings,\n>\n> * Georgios Kokolatos (gkokolatos@protonmail.com) wrote:\n> > The patch seems to be implementing a useful and requested feature.\n> > The patch applies cleanly and passes the basic regress tests. Also the\n> commitfest bot is happy.\n> >\n> > A first pass at the code, has not revealed any worthwhile comments.\n> > Please allow me for a second and more thorough pass. The commitfest has\n> hardly started after all.\n>\n> Great, thanks!\n>\n> > Also allow me a series of genuine questions:\n> >\n> > What would the behaviour be with REVOKE?\n> > In a sequence similar to:\n> > GRANT ALL ON ...\n>\n> GRANT ALL would be independently GRANT'ing rights to some role and\n> therefore unrelated.\n>\n> > REVOKE pg_read_all_data FROM ...\n>\n> This would simply REVOKE that role from the user. Privileges\n> independently GRANT'd directly to the user wouldn't be affected. Nor\n> would other role membership.\n>\n> > What privileges would the user be left with? Would it be possible to end\n> up in the same privilege only with a GRANT command?\n>\n> I'm not sure what's being asked here.\n>\n\nI think the core thing to remember here is that SQL permissions are always\nadditive, that's what confuses some cases.\n\nThat is, REVOKE something FROM role only removes this particular additive\npermission. It doesn't make sure the role doesn't have the same permission\n*through some other means*.\n\nSometime it would be really useful to be able to do e.g. \"DENY DELETE ON\nimportanttable FROM sfrost\", which would then override any DELETE\npermissions he'd be getting from anywhere else. To be able to say\n\"everybody except x\". But that's not something that's in SQL permissions\nAFAIK :)\n\n\n> Does the above scenario even make sense?\n>\n> I definitely believe it makes sense for a given role/user to be a member\n> of pg_read_all_data and to be a member of other roles, or to have other\n> privileges GRANT'd directly to them.\n>\n\nYeah, for example another role might have a combination of read and write\npermissions, and those would then remain for the user if pg_read_all_data\nis removed.\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 28, 2020 at 2:43 PM Stephen Frost <sfrost@snowman.net> wrote:Greetings,\n\n* Georgios Kokolatos (gkokolatos@protonmail.com) wrote:\n> The patch seems to be implementing a useful and requested feature.\n> The patch applies cleanly and passes the basic regress tests. Also the commitfest bot is happy.\n> \n> A first pass at the code, has not revealed any worthwhile comments.\n> Please allow me for a second and more thorough pass. The commitfest has hardly started after all.\n\nGreat, thanks!\n\n> Also allow me a series of genuine questions: \n> \n> What would the behaviour be with REVOKE?\n> In a sequence similar to:\n> GRANT ALL ON ...\n\nGRANT ALL would be independently GRANT'ing rights to some role and\ntherefore unrelated.\n\n> REVOKE pg_read_all_data FROM ...\n\nThis would simply REVOKE that role from the user.  Privileges\nindependently GRANT'd directly to the user wouldn't be affected.  Nor\nwould other role membership.\n\n> What privileges would the user be left with? Would it be possible to end up in the same privilege only with a GRANT command?\n\nI'm not sure what's being asked here.I think the core thing to remember here is that SQL permissions are always additive, that's what confuses some cases.That is, REVOKE something FROM role only removes this particular additive permission. It doesn't make sure the role doesn't have the same permission *through some other means*.Sometime it would be really useful to be able to do e.g. \"DENY DELETE ON importanttable FROM sfrost\", which would then override any DELETE permissions he'd be getting from anywhere else. To be able to say \"everybody except x\". But that's not something that's in SQL permissions AFAIK :)\n> Does the above scenario even make sense?\n\nI definitely believe it makes sense for a given role/user to be a member\nof pg_read_all_data and to be a member of other roles, or to have other\nprivileges GRANT'd directly to them.Yeah, for example another role might have a combination of read and write permissions, and those would then remain for the user if pg_read_all_data is removed. --  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Fri, 28 Aug 2020 14:53:15 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "Greetings,\n\n* Isaac Morland (isaac.morland@gmail.com) wrote:\n> On Fri, 28 Aug 2020 at 08:43, Stephen Frost <sfrost@snowman.net> wrote:\n> > This would simply REVOKE that role from the user. Privileges\n> > independently GRANT'd directly to the user wouldn't be affected. Nor\n> > would other role membership.\n> >\n> > > What privileges would the user be left with? Would it be possible to end\n> > up in the same privilege only with a GRANT command?\n> \n> What about:\n> \n> REVOKE SELECT ON [table] FROM pg_read_all_data;\n\nWouldn't have any effect, and I think that's correct.\n\n> I guess what I’m really asking is whether pg_read_all_data is automatically\n> granted SELECT on all newly-created relations, or if the permission\n> checking system always returns TRUE when asked if pg_read_all_data can\n> select from a relation? I’m guessing it’s the latter so that it would be\n> ineffective to revoke select privilege as I think this is more useful, but\n> I’d like to be sure and the documentation should be explicit on this point.\n\nYes, it's the latter. I'm not really sure about the documentation\nchange you're contemplating- have a specific suggestion?\n\nThanks,\n\nStephen", "msg_date": "Fri, 28 Aug 2020 08:54:11 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": true, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "\n\n\n\n\n‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn Friday, 28 August 2020 15:43, Stephen Frost <sfrost@snowman.net> wrote:\n\n> Greetings,\n>\n> - Georgios Kokolatos (gkokolatos@protonmail.com) wrote:\n>\n> > The patch seems to be implementing a useful and requested feature.\n> > The patch applies cleanly and passes the basic regress tests. Also the commitfest bot is happy.\n> > A first pass at the code, has not revealed any worthwhile comments.\n> > Please allow me for a second and more thorough pass. The commitfest has hardly started after all.\n>\n> Great, thanks!\n>\n> > Also allow me a series of genuine questions:\n> > What would the behaviour be with REVOKE?\n> > In a sequence similar to:\n> > GRANT ALL ON ...\n>\n> GRANT ALL would be independently GRANT'ing rights to some role and\n> therefore unrelated.\n>\n> > REVOKE pg_read_all_data FROM ...\n>\n> This would simply REVOKE that role from the user. Privileges\n> independently GRANT'd directly to the user wouldn't be affected. Nor\n> would other role membership.\n>\n> > What privileges would the user be left with? Would it be possible to end up in the same privilege only with a GRANT command?\n>\n> I'm not sure what's being asked here.\n\nYou are correct. My phrasing is not clear. Please be patient and allow me to try again.\n\nI was playing around with the code and I was trying a bit the opposite of what you have submitted in the test file.\n\nYou have, (snipped):\n\nGRANT pg_read_all_data TO regress_priv_user6;\n\nSET SESSION AUTHORIZATION regress_priv_user6;\nSELECT * FROM atest1; -- ok\nINSERT INTO atest2 VALUES ('foo', true); -- fail\n\n\nI was expecting:\nREVOKE pg_read_all_data FROM regress_priv_user6;\n\nSET SESSION AUTHORIZATION regress_priv_user6;\nSELECT * FROM atest1; -- fail\nINSERT INTO atest2 VALUES ('foo', true); -- ok\n\n\nMy expectation was not met since in my manual test (unless I made a mistake which is entirely possible), the SELECT above did not fail. The insert did succeed though.\n\nThe first question: Was my expectation wrong?\nThe second question: Is there a privilege that can be granted to regress_priv_user6 that will not permit the select operation but will permit the insert operation? If no, should there be one?\n\nI hope I am clearer now.\n\nThank you again for your patience.\n\n>\n> > Does the above scenario even make sense?\n>\n> I definitely believe it makes sense for a given role/user to be a member\n> of pg_read_all_data and to be a member of other roles, or to have other\n> privileges GRANT'd directly to them.\n>\n> Thanks,\n>\n> Stephen\n\n\n\n\n", "msg_date": "Fri, 28 Aug 2020 13:06:17 +0000", "msg_from": "gkokolatos@pm.me", "msg_from_op": false, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "Greetings,\n\n* gkokolatos@pm.me (gkokolatos@pm.me) wrote:\n> On Friday, 28 August 2020 15:43, Stephen Frost <sfrost@snowman.net> wrote:\n> > > What privileges would the user be left with? Would it be possible to end up in the same privilege only with a GRANT command?\n> >\n> > I'm not sure what's being asked here.\n> \n> You are correct. My phrasing is not clear. Please be patient and allow me to try again.\n> \n> I was playing around with the code and I was trying a bit the opposite of what you have submitted in the test file.\n> \n> You have, (snipped):\n> \n> GRANT pg_read_all_data TO regress_priv_user6;\n> \n> SET SESSION AUTHORIZATION regress_priv_user6;\n> SELECT * FROM atest1; -- ok\n> INSERT INTO atest2 VALUES ('foo', true); -- fail\n> \n> \n> I was expecting:\n> REVOKE pg_read_all_data FROM regress_priv_user6;\n\nAre you sure this REVOKE was successful..?\n\n> SET SESSION AUTHORIZATION regress_priv_user6;\n> SELECT * FROM atest1; -- fail\n> INSERT INTO atest2 VALUES ('foo', true); -- ok\n\n=# create role r1;\nCREATE ROLE\n=*# grant pg_read_all_data to r1;\nGRANT ROLE\n=*# create table t1 (c1 int);\nCREATE TABLE\n=*# set role r1;\n=*> select * from t1;\n c1 \n----\n(0 rows)\n=*> reset role;\nRESET\n=*# revoke pg_read_all_data from r1;\nREVOKE ROLE\n=*# set role r1;\nSET\n=*> select * from t1;\nERROR: permission denied for table t1\n\nSeems to be working as expected here.\n\n> My expectation was not met since in my manual test (unless I made a mistake which is entirely possible), the SELECT above did not fail. The insert did succeed though.\n\nThat the INSERT worked seems pretty odd- could you post the exact\nchanges you've made to the regression tests, or the exact script where\nyou aren't seeing what you expect? I've not been able to reproduce the\nGRANT allowing a user to INSERT into a table.\n\n> The first question: Was my expectation wrong?\n\nIf there aren't any other privileges involved, then REVOKE'ing the role\nfrom a user should prevent that user from being able to SELECT from the\ntable.\n\n> The second question: Is there a privilege that can be granted to regress_priv_user6 that will not permit the select operation but will permit the insert operation? If no, should there be one?\n\nGRANT INSERT ON atest1 TO regress_prive_user6; would allow just\nINSERT'ing.\n\nMagnus also brought up the idea of a 'write_all_data' role, but that's\npretty independent of this, imv. Not against adding it, if we can agree\nas to what it means, exactly, but we should probably discuss over in\nthat sub-thread.\n\nThanks,\n\nStephen", "msg_date": "Fri, 28 Aug 2020 09:18:56 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": true, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "On Fri, 28 Aug 2020 at 08:54, Stephen Frost <sfrost@snowman.net> wrote:\n\n>\n> Yes, it's the latter. I'm not really sure about the documentation\n> change you're contemplating- have a specific suggestion?\n>\n\nSorry, I was discussing this as if it was an abstract idea, not a concrete\npatch. I've just taken a look at the patch and I think the documentation in\ndoc/src/sgml/user-manag.sgml is OK.\n\nOn Fri, 28 Aug 2020 at 08:54, Stephen Frost <sfrost@snowman.net> wrote:\nYes, it's the latter.  I'm not really sure about the documentation\nchange you're contemplating- have a specific suggestion?Sorry, I was discussing this as if it was an abstract idea, not a concrete patch. I've just taken a look at the patch and I think the documentation in doc/src/sgml/user-manag.sgml is OK.", "msg_date": "Fri, 28 Aug 2020 09:24:34 -0400", "msg_from": "Isaac Morland <isaac.morland@gmail.com>", "msg_from_op": false, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "Greetings,\n\n* Magnus Hagander (magnus@hagander.net) wrote:\n> On Fri, Aug 28, 2020 at 2:38 PM Stephen Frost <sfrost@snowman.net> wrote:\n> > * Magnus Hagander (magnus@hagander.net) wrote:\n> > > Without having actually looked at the code, definite +1 for this feature.\n> > > It's much requested...\n> >\n> > Thanks.\n> >\n> > > But, should we also have a pg_write_all_data to go along with it?\n> >\n> > Perhaps, but could certainly be a different patch, and it'd need to be\n> > better defined, it seems to me... read_all is pretty straight-forward\n> > (the general goal being \"make pg_dumpall/pg_dump work\"), what would\n> > write mean? INSERT? DELETE? TRUNCATE? ALTER TABLE? System catalogs?\n> \n> Well, it's pg_write_all_*data*, so it certainly wouldn't be alter table or\n> system catalogs.\n> \n> I'd say insert/update/delete yes.\n> \n> TRUNCATE is always an outlier.Given it's generally classified as DDL, I\n> wouldn't include it.\n\nAlright, that seems like it'd be pretty easy. We already have a check\nin pg_class_aclmask to disallow modification of system catalogs w/o\nbeing a superuser, so we should be alright to add a similar check for\ninsert/update/delete just below where I added the SELECT check.\n\n> > Doesn't seem like you could just declare it to be 'allow pg_restore'\n> > either, as that might include creating untrusted functions, et al.\n> \n> No definitely not. That wouldn't be the usecase at all :)\n\nGood. :)\n\n> (and fwiw to me the main use case for read_all_data also isn't pg_dump,\n> because most people using pg_dump are already db owner or higher in my\n> experience. But it is nice that it helps with that too)\n\nGlad to have confirmation that there's other use-cases this helps with.\n\nI'll post an updated patch with that added in a day or two.\n\nThanks,\n\nStephen", "msg_date": "Fri, 28 Aug 2020 09:26:45 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": true, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "Le 28/08/2020 � 15:26, Stephen Frost a �crit�:\n> Greetings,\n>\n> * Magnus Hagander (magnus@hagander.net) wrote:\n>> On Fri, Aug 28, 2020 at 2:38 PM Stephen Frost <sfrost@snowman.net> wrote:\n>>> * Magnus Hagander (magnus@hagander.net) wrote:\n>>>> Without having actually looked at the code, definite +1 for this feature.\n>>>> It's much requested...\n>>> Thanks.\n>>>\n>>>> But, should we also have a pg_write_all_data to go along with it?\n>>> Perhaps, but could certainly be a different patch, and it'd need to be\n>>> better defined, it seems to me... read_all is pretty straight-forward\n>>> (the general goal being \"make pg_dumpall/pg_dump work\"), what would\n>>> write mean? INSERT? DELETE? TRUNCATE? ALTER TABLE? System catalogs?\n>> Well, it's pg_write_all_*data*, so it certainly wouldn't be alter table or\n>> system catalogs.\n>>\n>> I'd say insert/update/delete yes.\n>>\n>> TRUNCATE is always an outlier.Given it's generally classified as DDL, I\n>> wouldn't include it.\n> Alright, that seems like it'd be pretty easy. We already have a check\n> in pg_class_aclmask to disallow modification of system catalogs w/o\n> being a superuser, so we should be alright to add a similar check for\n> insert/update/delete just below where I added the SELECT check.\n>\n>>> Doesn't seem like you could just declare it to be 'allow pg_restore'\n>>> either, as that might include creating untrusted functions, et al.\n>> No definitely not. That wouldn't be the usecase at all :)\n> Good. :)\n>\n>> (and fwiw to me the main use case for read_all_data also isn't pg_dump,\n>> because most people using pg_dump are already db owner or higher in my\n>> experience. But it is nice that it helps with that too)\n> Glad to have confirmation that there's other use-cases this helps with.\n>\n> I'll post an updated patch with that added in a day or two.\n>\n> Thanks,\n>\n> Stephen\n\nHi,\n\n\nLooking at this thread I was thinking about the FDW. Does role \npg_read_all_data will allow to execute pg_dump with \n--include-foreign-data option? If this is the case how about priviledge \non fdw and foreign server? If this is the behavior we want I guess that \nthe modification should be applied to pg_foreign_data_wrapper_aclmask() \nand pg_foreign_server_aclmask() too.\n\n\nBest regards,\n\n-- \nGilles Darold\n\n\n\n", "msg_date": "Fri, 28 Aug 2020 15:58:58 +0200", "msg_from": "Gilles Darold <gilles@darold.net>", "msg_from_op": false, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "Greetings,\n\n* Gilles Darold (gilles@darold.net) wrote:\n> Le 28/08/2020 à 15:26, Stephen Frost a écrit :\n> >* Magnus Hagander (magnus@hagander.net) wrote:\n> >>On Fri, Aug 28, 2020 at 2:38 PM Stephen Frost <sfrost@snowman.net> wrote:\n> >>>* Magnus Hagander (magnus@hagander.net) wrote:\n> >>>>Without having actually looked at the code, definite +1 for this feature.\n> >>>>It's much requested...\n> >>>Thanks.\n> >>>\n> >>>>But, should we also have a pg_write_all_data to go along with it?\n> >>>Perhaps, but could certainly be a different patch, and it'd need to be\n> >>>better defined, it seems to me... read_all is pretty straight-forward\n> >>>(the general goal being \"make pg_dumpall/pg_dump work\"), what would\n> >>>write mean? INSERT? DELETE? TRUNCATE? ALTER TABLE? System catalogs?\n> >>Well, it's pg_write_all_*data*, so it certainly wouldn't be alter table or\n> >>system catalogs.\n> >>\n> >>I'd say insert/update/delete yes.\n> >>\n> >>TRUNCATE is always an outlier.Given it's generally classified as DDL, I\n> >>wouldn't include it.\n> >Alright, that seems like it'd be pretty easy. We already have a check\n> >in pg_class_aclmask to disallow modification of system catalogs w/o\n> >being a superuser, so we should be alright to add a similar check for\n> >insert/update/delete just below where I added the SELECT check.\n> >\n> >>>Doesn't seem like you could just declare it to be 'allow pg_restore'\n> >>>either, as that might include creating untrusted functions, et al.\n> >>No definitely not. That wouldn't be the usecase at all :)\n> >Good. :)\n> >\n> >>(and fwiw to me the main use case for read_all_data also isn't pg_dump,\n> >>because most people using pg_dump are already db owner or higher in my\n> >>experience. But it is nice that it helps with that too)\n> >Glad to have confirmation that there's other use-cases this helps with.\n> >\n> >I'll post an updated patch with that added in a day or two.\n> \n> Looking at this thread I was thinking about the FDW. Does role\n> pg_read_all_data will allow to execute pg_dump with --include-foreign-data\n> option? If this is the case how about priviledge on fdw and foreign server?\n> If this is the behavior we want I guess that the modification should be\n> applied to pg_foreign_data_wrapper_aclmask() and pg_foreign_server_aclmask()\n> too.\n\nUsing an FDW will often also require having a user mapping and there's\nno way for that to be accomplished through only GRANT'ing a default\nrole, so I don't think we should mix this specific role with the FDW\npermissions system.\n\nThanks,\n\nStephen", "msg_date": "Fri, 28 Aug 2020 10:52:19 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": true, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "Le 28/08/2020 � 16:52, Stephen Frost a �crit�:\n> Greetings,\n>\n> * Gilles Darold (gilles@darold.net) wrote:\n>> Le 28/08/2020 � 15:26, Stephen Frost a �crit�:\n>>> * Magnus Hagander (magnus@hagander.net) wrote:\n>>>> On Fri, Aug 28, 2020 at 2:38 PM Stephen Frost <sfrost@snowman.net> wrote:\n>>>>> * Magnus Hagander (magnus@hagander.net) wrote:\n>>>>>> Without having actually looked at the code, definite +1 for this feature.\n>>>>>> It's much requested...\n>>>>> Thanks.\n>>>>>\n>>>>>> But, should we also have a pg_write_all_data to go along with it?\n>>>>> Perhaps, but could certainly be a different patch, and it'd need to be\n>>>>> better defined, it seems to me... read_all is pretty straight-forward\n>>>>> (the general goal being \"make pg_dumpall/pg_dump work\"), what would\n>>>>> write mean? INSERT? DELETE? TRUNCATE? ALTER TABLE? System catalogs?\n>>>> Well, it's pg_write_all_*data*, so it certainly wouldn't be alter table or\n>>>> system catalogs.\n>>>>\n>>>> I'd say insert/update/delete yes.\n>>>>\n>>>> TRUNCATE is always an outlier.Given it's generally classified as DDL, I\n>>>> wouldn't include it.\n>>> Alright, that seems like it'd be pretty easy. We already have a check\n>>> in pg_class_aclmask to disallow modification of system catalogs w/o\n>>> being a superuser, so we should be alright to add a similar check for\n>>> insert/update/delete just below where I added the SELECT check.\n>>>\n>>>>> Doesn't seem like you could just declare it to be 'allow pg_restore'\n>>>>> either, as that might include creating untrusted functions, et al.\n>>>> No definitely not. That wouldn't be the usecase at all :)\n>>> Good. :)\n>>>\n>>>> (and fwiw to me the main use case for read_all_data also isn't pg_dump,\n>>>> because most people using pg_dump are already db owner or higher in my\n>>>> experience. But it is nice that it helps with that too)\n>>> Glad to have confirmation that there's other use-cases this helps with.\n>>>\n>>> I'll post an updated patch with that added in a day or two.\n>> Looking at this thread I was thinking about the FDW. Does role\n>> pg_read_all_data will allow to execute pg_dump with --include-foreign-data\n>> option? If this is the case how about priviledge on fdw and foreign server?\n>> If this is the behavior we want I guess that the modification should be\n>> applied to pg_foreign_data_wrapper_aclmask() and pg_foreign_server_aclmask()\n>> too.\n> Using an FDW will often also require having a user mapping and there's\n> no way for that to be accomplished through only GRANT'ing a default\n> role, so I don't think we should mix this specific role with the FDW\n> permissions system.\n\n\nI'm fine with that, perhaps it should be mentioned in the documentation \nthat foreign tables are not covered by this role.\n\n-- \nGilles Darold\n\n\n\n", "msg_date": "Fri, 28 Aug 2020 17:21:22 +0200", "msg_from": "Gilles Darold <gilles@darold.net>", "msg_from_op": false, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "Greetings,\n\n* Gilles Darold (gilles@darold.net) wrote:\n> Le 28/08/2020 à 16:52, Stephen Frost a écrit :\n> >Using an FDW will often also require having a user mapping and there's\n> >no way for that to be accomplished through only GRANT'ing a default\n> >role, so I don't think we should mix this specific role with the FDW\n> >permissions system.\n> \n> I'm fine with that, perhaps it should be mentioned in the documentation that\n> foreign tables are not covered by this role.\n\nWe could say it doesn't GRANT CONNECT rights on databases, or EXECUTE on\nfunctions too, but that doesn't seem like a terribly good approach for\nthe documentation to take- instead we document specifically what IS\nincluded, which seems sufficiently clear to me.\n\nThanks,\n\nStephen", "msg_date": "Fri, 28 Aug 2020 13:25:32 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": true, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "Greetings,\n\n* Stephen Frost (sfrost@snowman.net) wrote:\n> * Magnus Hagander (magnus@hagander.net) wrote:\n> > On Fri, Aug 28, 2020 at 2:38 PM Stephen Frost <sfrost@snowman.net> wrote:\n> > > * Magnus Hagander (magnus@hagander.net) wrote:\n> > > > Without having actually looked at the code, definite +1 for this feature.\n> > > > It's much requested...\n> > >\n> > > Thanks.\n> > >\n> > > > But, should we also have a pg_write_all_data to go along with it?\n> > >\n> > > Perhaps, but could certainly be a different patch, and it'd need to be\n> > > better defined, it seems to me... read_all is pretty straight-forward\n> > > (the general goal being \"make pg_dumpall/pg_dump work\"), what would\n> > > write mean? INSERT? DELETE? TRUNCATE? ALTER TABLE? System catalogs?\n> > \n> > Well, it's pg_write_all_*data*, so it certainly wouldn't be alter table or\n> > system catalogs.\n> > \n> > I'd say insert/update/delete yes.\n> > \n> > TRUNCATE is always an outlier.Given it's generally classified as DDL, I\n> > wouldn't include it.\n> \n> Alright, that seems like it'd be pretty easy. We already have a check\n> in pg_class_aclmask to disallow modification of system catalogs w/o\n> being a superuser, so we should be alright to add a similar check for\n> insert/update/delete just below where I added the SELECT check.\n> \n> > > Doesn't seem like you could just declare it to be 'allow pg_restore'\n> > > either, as that might include creating untrusted functions, et al.\n> > \n> > No definitely not. That wouldn't be the usecase at all :)\n> \n> Good. :)\n> \n> > (and fwiw to me the main use case for read_all_data also isn't pg_dump,\n> > because most people using pg_dump are already db owner or higher in my\n> > experience. But it is nice that it helps with that too)\n> \n> Glad to have confirmation that there's other use-cases this helps with.\n> \n> I'll post an updated patch with that added in a day or two.\n\nHere's that updated patch, comments welcome.\n\nThanks!\n\nStephen", "msg_date": "Sun, 30 Aug 2020 19:20:01 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": true, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn Monday, 31 August 2020 02:20, Stephen Frost <sfrost@snowman.net> wrote:\n\n> Greetings,\n>\n> - Stephen Frost (sfrost@snowman.net) wrote:\n>\n> > - Magnus Hagander (magnus@hagander.net) wrote:\n> >\n> > > On Fri, Aug 28, 2020 at 2:38 PM Stephen Frost sfrost@snowman.net wrote:\n> > >\n> > > > - Magnus Hagander (magnus@hagander.net) wrote:\n> > > >\n> > > > > Without having actually looked at the code, definite +1 for this feature.\n> > > > > It's much requested...\n> > > >\n> > > > Thanks.\n> > > >\n> > > > > But, should we also have a pg_write_all_data to go along with it?\n> > > >\n> > > > Perhaps, but could certainly be a different patch, and it'd need to be\n> > > > better defined, it seems to me... read_all is pretty straight-forward\n> > > > (the general goal being \"make pg_dumpall/pg_dump work\"), what would\n> > > > write mean? INSERT? DELETE? TRUNCATE? ALTER TABLE? System catalogs?\n> > >\n> > > Well, it's pg_write_all_data, so it certainly wouldn't be alter table or\n> > > system catalogs.\n> > > I'd say insert/update/delete yes.\n> > > TRUNCATE is always an outlier.Given it's generally classified as DDL, I\n> > > wouldn't include it.\n> >\n> > Alright, that seems like it'd be pretty easy. We already have a check\n> > in pg_class_aclmask to disallow modification of system catalogs w/o\n> > being a superuser, so we should be alright to add a similar check for\n> > insert/update/delete just below where I added the SELECT check.\n> >\n> > > > Doesn't seem like you could just declare it to be 'allow pg_restore'\n> > > > either, as that might include creating untrusted functions, et al.\n> > >\n> > > No definitely not. That wouldn't be the usecase at all :)\n> >\n> > Good. :)\n> >\n> > > (and fwiw to me the main use case for read_all_data also isn't pg_dump,\n> > > because most people using pg_dump are already db owner or higher in my\n> > > experience. But it is nice that it helps with that too)\n> >\n> > Glad to have confirmation that there's other use-cases this helps with.\n> > I'll post an updated patch with that added in a day or two.\n>\n> Here's that updated patch, comments welcome.\n\nThank you for the updated patch!\n\nHad a quick look on it and nothing stands out.\n\nAlso this sub-thread seems to have clearly responded on my early thoughts regarding invoking. Adding part of that subthread bellow:\n\n\n>> My expectation was not met since in my manual test (unless I made a mistake which is entirely possible), the SELECT above did not fail. The insert did succeed though.\n\n> That the INSERT worked seems pretty odd- could you post the exact\n> changes you've made to the regression tests, or the exact script where\n> you aren't seeing what you expect? I've not been able to reproduce the\n> GRANT allowing a user to INSERT into a table.\n\n>> The first question: Was my expectation wrong?\n\n> If there aren't any other privileges involved, then REVOKE'ing the role\n> from a user should prevent that user from being able to SELECT from the\n> table.\n\n>> The second question: Is there a privilege that can be granted to regress_priv_user6 that will not permit the select operation but will permit the insert operation? If no, should there be one?\n\nAs discussed above, while I was struggling to formulate the thought, Magnus had already proposed pg_write_all_data and the community had reached a consensus on what it actually means.\n\nPlease find attached a minimal test case and the output of it.\n\nIt is obvious that I was confused and added confusion to the thread. Permissions are additive and autonomous. Now it is rather clear to me what the expectations are and how the patch should behave.\n\nTo add to my embarrassment, the REVOKE operation emitted a warning which I had clearly missed.\n\nApologies.\n\n//Georgios\n\n>\n> Thanks!\n>\n> Stephen", "msg_date": "Mon, 31 Aug 2020 14:17:12 +0000", "msg_from": "gkokolatos@pm.me", "msg_from_op": false, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "The following review has been posted through the commitfest application:\nmake installcheck-world: tested, passed\nImplements feature: not tested\nSpec compliant: not tested\nDocumentation: not tested\n\nVersion 2 of the patch, implements a useful feature. Based on the mailing list discussion, it is also a feature that the community desires.\r\n\r\nThe code seems to be correct and it follows the style. The patch comes complete with tests and documentation.\r\n\r\nAs a non native English speaker, I did not notice any syntactical or grammatical errors in the documentation. Yet it should not mean a lot.\r\n\r\nAs far as I am concerned, this version of the patch is ready for a committer.\r\n\r\nPlease feel free to contest my review, if you think I am wrong.\n\nThe new status of this patch is: Ready for Committer\n", "msg_date": "Tue, 01 Sep 2020 10:55:12 +0000", "msg_from": "Georgios Kokolatos <gkokolatos@protonmail.com>", "msg_from_op": false, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "Hi,\r\n\r\nthis patch is in \"Ready for committer\" state and the Cfbot is happy.\r\n\r\nIs there any committer that is available for taking a look at it?\r\n\r\nCheers,\r\n//Georgios - CFM 2020-11", "msg_date": "Thu, 29 Oct 2020 11:27:54 +0000", "msg_from": "Georgios Kokolatos <gkokolatos@protonmail.com>", "msg_from_op": false, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "Greetings,\n\n* Georgios Kokolatos (gkokolatos@protonmail.com) wrote:\n> this patch is in \"Ready for committer\" state and the Cfbot is happy.\n\nGlad that's still the case. :)\n\n> Is there any committer that is available for taking a look at it?\n\nIf there aren't any objections or further comments, I'll take another\nlook through it and will commit it during the upcoming CF.\n\nThanks!\n\nStephen", "msg_date": "Thu, 29 Oct 2020 10:19:59 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": true, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "On 29.10.2020 17:19, Stephen Frost wrote:\n> Greetings,\n>\n> * Georgios Kokolatos (gkokolatos@protonmail.com) wrote:\n>> this patch is in \"Ready for committer\" state and the Cfbot is happy.\n> Glad that's still the case. :)\n>\n>> Is there any committer that is available for taking a look at it?\n> If there aren't any objections or further comments, I'll take another\n> look through it and will commit it during the upcoming CF.\n>\n> Thanks!\n>\n> Stephen\n\nCFM reminder. Just in case you forgot about this thread)\nThe commitfest is heading to the end. And there was a plenty of time for \nanyone to object.\n\n-- \nAnastasia Lubennikova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Tue, 24 Nov 2020 01:08:35 +0300", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "Greetings,\n\n* Anastasia Lubennikova (a.lubennikova@postgrespro.ru) wrote:\n> On 29.10.2020 17:19, Stephen Frost wrote:\n> >* Georgios Kokolatos (gkokolatos@protonmail.com) wrote:\n> >>this patch is in \"Ready for committer\" state and the Cfbot is happy.\n> >Glad that's still the case. :)\n> >\n> >>Is there any committer that is available for taking a look at it?\n> >If there aren't any objections or further comments, I'll take another\n> >look through it and will commit it during the upcoming CF.\n> >\n> >Thanks!\n> >\n> >Stephen\n> \n> CFM reminder. Just in case you forgot about this thread)\n> The commitfest is heading to the end. And there was a plenty of time for\n> anyone to object.\n\nThanks, I've not forgotten, but it's a bit complicated given that I've\nanother patch in progress to rename default roles to be predefined\nroles which conflicts with this one. Hopefully we'll have a few\ncomments on that and I can get it committed and this one updated with\nthe new naming. I'd rather not commit this one and then immediately\ncommit changes over top of it.\n\nThanks again!\n\nStephen", "msg_date": "Mon, 23 Nov 2020 17:31:47 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": true, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "Hi,\n\n\n\n\n‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn Monday, November 23, 2020 11:31 PM, Stephen Frost <sfrost@snowman.net> wrote:\n\n> Greetings,\n>\n> - Anastasia Lubennikova (a.lubennikova@postgrespro.ru) wrote:\n>\n> > On 29.10.2020 17:19, Stephen Frost wrote:\n> >\n> > > - Georgios Kokolatos (gkokolatos@protonmail.com) wrote:\n> > >\n> > > > this patch is in \"Ready for committer\" state and the Cfbot is happy.\n> > > > Glad that's still the case. :)\n> > >\n> > > > Is there any committer that is available for taking a look at it?\n> > > > If there aren't any objections or further comments, I'll take another\n> > > > look through it and will commit it during the upcoming CF.\n> > >\n> > > Thanks!\n> > > Stephen\n> >\n> > CFM reminder. Just in case you forgot about this thread)\n> > The commitfest is heading to the end. And there was a plenty of time for\n> > anyone to object.\n>\n> Thanks, I've not forgotten, but it's a bit complicated given that I've\n> another patch in progress to rename default roles to be predefined\n> roles which conflicts with this one. Hopefully we'll have a few\n> comments on that and I can get it committed and this one updated with\n> the new naming. I'd rather not commit this one and then immediately\n> commit changes over top of it.\n\nMay I enquire about the status of the current?\n\n\n//Georgios\n\n>\n> Thanks again!\n>\n> Stephen\n\n\n\n\n", "msg_date": "Thu, 04 Mar 2021 14:47:18 +0000", "msg_from": "gkokolatos@pm.me", "msg_from_op": false, "msg_subject": "Re: New default role- 'pg_read_all_data'" }, { "msg_contents": "Greetings,\n\n* gkokolatos@pm.me (gkokolatos@pm.me) wrote:\n> On Monday, November 23, 2020 11:31 PM, Stephen Frost <sfrost@snowman.net> wrote:\n> > - Anastasia Lubennikova (a.lubennikova@postgrespro.ru) wrote:\n> >\n> > > On 29.10.2020 17:19, Stephen Frost wrote:\n> > >\n> > > > - Georgios Kokolatos (gkokolatos@protonmail.com) wrote:\n> > > >\n> > > > > this patch is in \"Ready for committer\" state and the Cfbot is happy.\n> > > > > Glad that's still the case. :)\n> > > >\n> > > > > Is there any committer that is available for taking a look at it?\n> > > > > If there aren't any objections or further comments, I'll take another\n> > > > > look through it and will commit it during the upcoming CF.\n> > >\n> > > CFM reminder. Just in case you forgot about this thread)\n> > > The commitfest is heading to the end. And there was a plenty of time for\n> > > anyone to object.\n> >\n> > Thanks, I've not forgotten, but it's a bit complicated given that I've\n> > another patch in progress to rename default roles to be predefined\n> > roles which conflicts with this one. Hopefully we'll have a few\n> > comments on that and I can get it committed and this one updated with\n> > the new naming. I'd rather not commit this one and then immediately\n> > commit changes over top of it.\n> \n> May I enquire about the status of the current?\n\nThe patch to rename default roles to predefined roles for v14 has gone\nin, and so I've come back to this patch to add the\npg_read/write_all_data roles.\n\nHaving contemplated a bit further, I ended up deciding that it made more\nsense for these predefined roles to *not* have BYPASSRLS, which gives\nadmins the flexibilty to choose if they actually want RLS to be\nbypassed, or not, on the roles who they GRANT these roles to (if we just\nalways had bypassrls set, then they wouldn't have any choice but to\naccept that, which doesn't seem very kind). I've updated the\ndocumentation to make a note of that and to encourage admins who use\nthese roles to consider if they want to set BYPASSRLS on the actual\nlogin role which they'll have to create in order to use these roles\n(since they can't be used to login directly).\n\nUpdated patch attached. Will be playing with it a bit more but\ngenerally feel like it's in pretty good shape. Unless there's anything\nfurther on this, I'll likely commit it over the weekend.\n\nThanks!\n\nStephen", "msg_date": "Thu, 1 Apr 2021 16:00:06 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": true, "msg_subject": "Re: New predefined roles- 'pg_read/write_all_data'" }, { "msg_contents": "Greetings,\n\n* Stephen Frost (sfrost@snowman.net) wrote:\n> Updated patch attached. Will be playing with it a bit more but\n> generally feel like it's in pretty good shape. Unless there's anything\n> further on this, I'll likely commit it over the weekend.\n\nWeekend ended up being a bit busy, but I've now pushed this.\n\nThanks!\n\nStephen", "msg_date": "Mon, 5 Apr 2021 13:46:26 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": true, "msg_subject": "Re: New predefined roles- 'pg_read/write_all_data'" }, { "msg_contents": "Hi,\n\nOn Thu, Apr 01, 2021 at 04:00:06PM -0400, Stephen Frost wrote:\n> diff --git a/doc/src/sgml/user-manag.sgml b/doc/src/sgml/user-manag.sgml\n> index d171b13236..fe0bdb7599 100644\n> --- a/doc/src/sgml/user-manag.sgml\n> +++ b/doc/src/sgml/user-manag.sgml\n> @@ -518,6 +518,24 @@ DROP ROLE doomed_role;\n> </row>\n> </thead>\n> <tbody>\n> + <row>\n> + <entry>pg_read_all_data</entry>\n> + <entry>Read all data (tables, views, sequences), as if having SELECT\n> + rights on those objects, and USAGE rights on all schemas, even without\n> + having it explicitly. This role does not have the role attribute\n> + <literal>BYPASSRLS</literal> set. If RLS is being used, an administrator\n> + may wish to set <literal>BYPASSRLS</literal> on roles which this role is\n> + GRANTed to.</entry>\n> + </row>\n> + <row>\n> + <entry>pg_write_all_data</entry>\n> + <entry>Write all data (tables, views, sequences), as if having INSERT,\n> + UPDATE, and DELETE rights on those objects, and USAGE rights on all\n> + schemas, even without having it explicitly. This role does not have the\n> + role attribute <literal>BYPASSRLS</literal> set. If RLS is being used,\n> + an administrator may wish to set <literal>BYPASSRLS</literal> on roles\n> + which this role is GRANTed to.</entry>\n> + </row>\n\nShouldn't those \"SELECT\", \"INSERT\" etc. be wrapped in <command> tags?\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, Sascha Heuer\n\nUnser Umgang mit personenbezogenen Daten unterliegt\nfolgenden Bestimmungen: https://www.credativ.de/datenschutz\n\n\n", "msg_date": "Wed, 7 Apr 2021 12:36:11 +0200", "msg_from": "Michael Banck <michael.banck@credativ.de>", "msg_from_op": false, "msg_subject": "Re: New predefined roles- 'pg_read/write_all_data'" }, { "msg_contents": "Greetings,\n\n* Michael Banck (michael.banck@credativ.de) wrote:\n> On Thu, Apr 01, 2021 at 04:00:06PM -0400, Stephen Frost wrote:\n> > diff --git a/doc/src/sgml/user-manag.sgml b/doc/src/sgml/user-manag.sgml\n> > index d171b13236..fe0bdb7599 100644\n> > --- a/doc/src/sgml/user-manag.sgml\n> > +++ b/doc/src/sgml/user-manag.sgml\n> > @@ -518,6 +518,24 @@ DROP ROLE doomed_role;\n> > </row>\n> > </thead>\n> > <tbody>\n> > + <row>\n> > + <entry>pg_read_all_data</entry>\n> > + <entry>Read all data (tables, views, sequences), as if having SELECT\n> > + rights on those objects, and USAGE rights on all schemas, even without\n> > + having it explicitly. This role does not have the role attribute\n> > + <literal>BYPASSRLS</literal> set. If RLS is being used, an administrator\n> > + may wish to set <literal>BYPASSRLS</literal> on roles which this role is\n> > + GRANTed to.</entry>\n> > + </row>\n> > + <row>\n> > + <entry>pg_write_all_data</entry>\n> > + <entry>Write all data (tables, views, sequences), as if having INSERT,\n> > + UPDATE, and DELETE rights on those objects, and USAGE rights on all\n> > + schemas, even without having it explicitly. This role does not have the\n> > + role attribute <literal>BYPASSRLS</literal> set. If RLS is being used,\n> > + an administrator may wish to set <literal>BYPASSRLS</literal> on roles\n> > + which this role is GRANTed to.</entry>\n> > + </row>\n> \n> Shouldn't those \"SELECT\", \"INSERT\" etc. be wrapped in <command> tags?\n\nYeah, good point, fixed.\n\nThanks!\n\nStephen", "msg_date": "Fri, 27 Aug 2021 18:33:33 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": true, "msg_subject": "Re: New predefined roles- 'pg_read/write_all_data'" }, { "msg_contents": "Hi hackers,\n\nI have tested this new feature with PostgreSQL 14 Beta 3 environment.\nI created a user granted with pg_write_all_data role and executed UPDATE and DELETE statements on tables owned by other users.\nIf there is no WHERE clause, it can be executed as expected, but if the WHERE clause is specified, an error of permission denied will occur.\nIs this the expected behavior?\nThe WHERE clause is not specified in the regression test (privileges.sql).\n\nBelow is the execution log.\n------------------------------------------------\npostgres=# CREATE USER owner1 PASSWORD 'owner1';\nCREATE ROLE\npostgres=# CREATE USER write1 PASSWORD 'write1';\nCREATE ROLE\npostgres=# GRANT pg_write_all_data TO write1;\nGRANT ROLE\npostgres=# SET SESSION AUTHORIZATION owner1;\nSET\npostgres=> CREATE TABLE data1(c1 INT, c2 VARCHAR(10));\nCREATE TABLE\npostgres=> INSERT INTO data1 VALUES (generate_series(1, 10), 'data1');\nINSERT 0 10\npostgres=> SET SESSION AUTHORIZATION write1;\nSET\npostgres=> INSERT INTO data1 VALUES (0, 'data1');\t-- success\nINSERT 0 1\npostgres=> UPDATE data1 SET c2='update' WHERE c1=0;\t-- fail\nERROR: permission denied for table data1\npostgres=> DELETE FROM data1 WHERE c1=0;\t-- fail\nERROR: permission denied for table data1\npostgres=> UPDATE data1 SET c2='update';\t-- success\nUPDATE 11\npostgres=> DELETE FROM data1;\t-- success\nDELETE 11\npostgres=> SELECT version();\n version\n------------------------------------------------------------------------------------------------------------\n PostgreSQL 14beta3 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39), 64-bit\n(1 row)\n-------------\n\nRegards,\nNoriyoshi Shinoda\n\n-----Original Message-----\nFrom: Stephen Frost [mailto:sfrost@snowman.net] \nSent: Saturday, August 28, 2021 7:34 AM\nTo: Michael Banck <michael.banck@credativ.de>\nCc: gkokolatos@pm.me; Anastasia Lubennikova <a.lubennikova@postgrespro.ru>; pgsql-hackers@lists.postgresql.org\nSubject: Re: New predefined roles- 'pg_read/write_all_data'\n\nGreetings,\n\n* Michael Banck (michael.banck@credativ.de) wrote:\n> On Thu, Apr 01, 2021 at 04:00:06PM -0400, Stephen Frost wrote:\n> > diff --git a/doc/src/sgml/user-manag.sgml \n> > b/doc/src/sgml/user-manag.sgml index d171b13236..fe0bdb7599 100644\n> > --- a/doc/src/sgml/user-manag.sgml\n> > +++ b/doc/src/sgml/user-manag.sgml\n> > @@ -518,6 +518,24 @@ DROP ROLE doomed_role;\n> > </row>\n> > </thead>\n> > <tbody>\n> > + <row>\n> > + <entry>pg_read_all_data</entry>\n> > + <entry>Read all data (tables, views, sequences), as if having SELECT\n> > + rights on those objects, and USAGE rights on all schemas, even without\n> > + having it explicitly. This role does not have the role attribute\n> > + <literal>BYPASSRLS</literal> set. If RLS is being used, an administrator\n> > + may wish to set <literal>BYPASSRLS</literal> on roles which this role is\n> > + GRANTed to.</entry>\n> > + </row>\n> > + <row>\n> > + <entry>pg_write_all_data</entry>\n> > + <entry>Write all data (tables, views, sequences), as if having INSERT,\n> > + UPDATE, and DELETE rights on those objects, and USAGE rights on all\n> > + schemas, even without having it explicitly. This role does not have the\n> > + role attribute <literal>BYPASSRLS</literal> set. If RLS is being used,\n> > + an administrator may wish to set <literal>BYPASSRLS</literal> on roles\n> > + which this role is GRANTed to.</entry>\n> > + </row>\n> \n> Shouldn't those \"SELECT\", \"INSERT\" etc. be wrapped in <command> tags?\n\nYeah, good point, fixed.\n\nThanks!\n\nStephen\n\n\n", "msg_date": "Sun, 5 Sep 2021 11:42:47 +0000", "msg_from": "\"Shinoda, Noriyoshi (PN Japan FSIP)\" <noriyoshi.shinoda@hpe.com>", "msg_from_op": false, "msg_subject": "RE: New predefined roles- 'pg_read/write_all_data'" }, { "msg_contents": "Greetings,\n\nOn Sun, Sep 5, 2021 at 07:43 Shinoda, Noriyoshi (PN Japan FSIP) <\nnoriyoshi.shinoda@hpe.com> wrote:\n\n> I have tested this new feature with PostgreSQL 14 Beta 3 environment.\n> I created a user granted with pg_write_all_data role and executed UPDATE\n> and DELETE statements on tables owned by other users.\n> If there is no WHERE clause, it can be executed as expected, but if the\n> WHERE clause is specified, an error of permission denied will occur.\n> Is this the expected behavior?\n\n\nA WHERE clause requires SELECT rights on the table/columns referenced and\nif no SELECT rights were granted then a permission denied error is the\ncorrect result, yes. Note that pg_write_all_data, as documented, does not\ninclude SELECT rights.\n\nThanks,\n\nStephen\n\nGreetings,On Sun, Sep 5, 2021 at 07:43 Shinoda, Noriyoshi (PN Japan FSIP) <noriyoshi.shinoda@hpe.com> wrote:\nI have tested this new feature with PostgreSQL 14 Beta 3 environment.\nI created a user granted with pg_write_all_data role and executed UPDATE and DELETE statements on tables owned by other users.\nIf there is no WHERE clause, it can be executed as expected, but if the WHERE clause is specified, an error of permission denied will occur.\nIs this the expected behavior?A WHERE clause requires SELECT rights on the table/columns referenced and if no SELECT rights were granted then a permission denied error is the correct result, yes. Note that pg_write_all_data, as documented, does not include SELECT rights. Thanks,Stephen", "msg_date": "Sun, 5 Sep 2021 07:50:05 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": true, "msg_subject": "Re: New predefined roles- 'pg_read/write_all_data'" }, { "msg_contents": "Thank you for your quick response.\r\nI understood the specifications from your explanation.\r\n\r\nRegards,\r\nNoriyoshi Shinoda\r\n\r\nFrom: Stephen Frost [mailto:sfrost@snowman.net]\r\nSent: Sunday, September 5, 2021 8:50 PM\r\nTo: Shinoda, Noriyoshi (PN Japan FSIP) <noriyoshi.shinoda@hpe.com>\r\nCc: Anastasia Lubennikova <a.lubennikova@postgrespro.ru>; Michael Banck <michael.banck@credativ.de>; gkokolatos@pm.me; pgsql-hackers@lists.postgresql.org\r\nSubject: Re: New predefined roles- 'pg_read/write_all_data'\r\n\r\nGreetings,\r\n\r\nOn Sun, Sep 5, 2021 at 07:43 Shinoda, Noriyoshi (PN Japan FSIP) <noriyoshi.shinoda@hpe.com<mailto:noriyoshi.shinoda@hpe.com>> wrote:\r\nI have tested this new feature with PostgreSQL 14 Beta 3 environment.\r\nI created a user granted with pg_write_all_data role and executed UPDATE and DELETE statements on tables owned by other users.\r\nIf there is no WHERE clause, it can be executed as expected, but if the WHERE clause is specified, an error of permission denied will occur.\r\nIs this the expected behavior?\r\n\r\nA WHERE clause requires SELECT rights on the table/columns referenced and if no SELECT rights were granted then a permission denied error is the correct result, yes. Note that pg_write_all_data, as documented, does not include SELECT rights.\r\n\r\nThanks,\r\n\r\nStephen\r\n\n\n\n\n\n\n\n\n\nThank you for your quick response.\nI understood the specifications from your explanation.\n \nRegards,\nNoriyoshi Shinoda\n \nFrom: Stephen Frost [mailto:sfrost@snowman.net]\r\n\nSent: Sunday, September 5, 2021 8:50 PM\nTo: Shinoda, Noriyoshi (PN Japan FSIP) <noriyoshi.shinoda@hpe.com>\nCc: Anastasia Lubennikova <a.lubennikova@postgrespro.ru>; Michael Banck <michael.banck@credativ.de>; gkokolatos@pm.me; pgsql-hackers@lists.postgresql.org\nSubject: Re: New predefined roles- 'pg_read/write_all_data'\n \n\nGreetings,\n\n\n \n\n\nOn Sun, Sep 5, 2021 at 07:43 Shinoda, Noriyoshi (PN Japan FSIP) <noriyoshi.shinoda@hpe.com> wrote:\n\n\n\n\nI have tested this new feature with PostgreSQL 14 Beta 3 environment.\r\nI created a user granted with pg_write_all_data role and executed UPDATE and DELETE statements on tables owned by other users.\r\nIf there is no WHERE clause, it can be executed as expected, but if the WHERE clause is specified, an error of permission denied will occur.\r\nIs this the expected behavior?\n\n\n \n\n\n\nA WHERE clause requires SELECT rights on the table/columns referenced and if no SELECT rights were granted then a permission denied error is the correct result, yes. Note that pg_write_all_data, as documented,\r\n does not include SELECT rights. \n\n\n \n\n\nThanks,\n\n\n \n\n\nStephen", "msg_date": "Sun, 5 Sep 2021 23:53:36 +0000", "msg_from": "\"Shinoda, Noriyoshi (PN Japan FSIP)\" <noriyoshi.shinoda@hpe.com>", "msg_from_op": false, "msg_subject": "RE: New predefined roles- 'pg_read/write_all_data'" } ]
[ { "msg_contents": "It strikes me that when we are vacuuming a temporary table (which\nnecessarily will be one of our own session), we don't really need\nto care what the global xmin horizon is. If we're not inside a\nuser transaction block, then there are no tuples in the table that\ncould be in-doubt anymore. Neither are there any snapshots in our\nsession that could see any dead tuples. Nor do we give a fig what\nother sessions might think of those tuples. So we could just set\nthe xmin cutoff as aggressively as possible, which is to say\nequal to the nextXid counter. While vacuuming a temp table is\nperhaps not something people do very often, I think when they do\ndo it they would like us to clean out all the dead tuples not just\nsome.\n\nHence I propose 0001 attached. 80% of it is just API additions to allow\npassing down the isTopLevel flag so that we can do the right thing in\nthe CLUSTER case; the important change is in vacuum_set_xid_limits.\n(For ease of review, I didn't reindent the existing code in\nvacuum_set_xid_limits, but that would be something to do before commit.)\n\nThe reason I got interested in this is that yesterday while fooling\nwith bug #16595, I was annoyed about our poor code test coverage in\naccess/gin/. The 0002 patch attached brings coverage for ginvacuum.c\nup from 59% to 93%; but as things stand, a long delay has to be inserted\nbetween the DELETE and VACUUM steps, else the VACUUM won't remove the\ndead tuples because of concurrent transactions, and we get no coverage\nimprovement. Since the table in question is a temp table, that seems\npretty silly.\n\nThoughts? Am I missing something important here?\n\n\t\t\tregards, tom lane", "msg_date": "Fri, 28 Aug 2020 11:46:49 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "More aggressive vacuuming of temporary tables" }, { "msg_contents": "On Fri, Aug 28, 2020 at 11:46:49AM -0400, Tom Lane wrote:\n> Hence I propose 0001 attached. 80% of it is just API additions to allow\n> passing down the isTopLevel flag so that we can do the right thing in\n> the CLUSTER case; the important change is in vacuum_set_xid_limits.\n> (For ease of review, I didn't reindent the existing code in\n> vacuum_set_xid_limits, but that would be something to do before commit.)\n\nI got to wonder lately if we should not have a static state like what\nwe do for MyXactFlags to track down if a utility query is a top-level\none or not as most of the time we just want to check the flag as\npassed down by standard_ProcessUtility(). I have faced this problem\nas well lately when pushing down a PreventInTransactionBlock() for\nsome stuff with REINDEX for example. Not sure how reliable this would\nbe though.. Passing isTopLevel down the road is a no-brainer, and\nperhaps having a static value would create more problems than it\nsolves in practice.\n--\nMichael", "msg_date": "Sat, 29 Aug 2020 10:43:18 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: More aggressive vacuuming of temporary tables" }, { "msg_contents": "Michael Paquier <michael@paquier.xyz> writes:\n> I got to wonder lately if we should not have a static state like what\n> we do for MyXactFlags to track down if a utility query is a top-level\n> one or not as most of the time we just want to check the flag as\n> passed down by standard_ProcessUtility(). I have faced this problem\n> as well lately when pushing down a PreventInTransactionBlock() for\n> some stuff with REINDEX for example. Not sure how reliable this would\n> be though.. Passing isTopLevel down the road is a no-brainer, and\n> perhaps having a static value would create more problems than it\n> solves in practice.\n\nHm. I suppose you'd need a PG_TRY block to ensure that the setting\ngot restored correctly after an error, so maintaining it that way\nwould be rather expensive. Also it just doesn't seem like\ntransaction-wide state, so having a static for it feels like the\nwrong thing.\n\n[thinks for awhile...] Would it make any sense to mark Portals as being\ntop-level or not, and then code that needs this info could look to\n\"ActivePortal->isTopLevel\"? We are already paying the PG_TRY overhead\nto maintain the ActivePortal variable safely. I'm not sure though\nwhether the Portal is granular enough. Do we set up a separate\nPortal for subcommands?\n\nIn the big scheme of things, though, we don't need this info in so\nmany places that passing it down as a parameter is an undue burden.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 29 Aug 2020 12:17:54 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: More aggressive vacuuming of temporary tables" }, { "msg_contents": "Hi,\n\nOn 2020-08-28 11:46:49 -0400, Tom Lane wrote:\n> It strikes me that when we are vacuuming a temporary table (which\n> necessarily will be one of our own session), we don't really need\n> to care what the global xmin horizon is. If we're not inside a\n> user transaction block, then there are no tuples in the table that\n> could be in-doubt anymore. Neither are there any snapshots in our\n> session that could see any dead tuples. Nor do we give a fig what\n> other sessions might think of those tuples. So we could just set\n> the xmin cutoff as aggressively as possible, which is to say\n> equal to the nextXid counter. While vacuuming a temp table is\n> perhaps not something people do very often, I think when they do\n> do it they would like us to clean out all the dead tuples not just\n> some.\n\nThat seems like a good idea.\n\nI've been toying with a patch that introduces more smarts about when a\nrow is removable, by looking more closely whether a specific row\nversions are visible (e.g. in the common case of one old snapshot and\nlots of newer rows). But that's orders of magnitude more complicated. So\ngoing for something as simple as this seems like a good idea.\n\n\n> Hence I propose 0001 attached. 80% of it is just API additions to allow\n> passing down the isTopLevel flag so that we can do the right thing in\n> the CLUSTER case; the important change is in vacuum_set_xid_limits.\n> (For ease of review, I didn't reindent the existing code in\n> vacuum_set_xid_limits, but that would be something to do before commit.)\n\nI did wonder for a moment if it could be worthwhile to just implement\nthis for VACUUM and leave CLUSTER alone, to avoid having to deal with\nthe toplevel stuff. But I think it's better to be consistent.\n\nBut now I do wonder why we need to know whether the command is top level\nor not? Why isn't the correct thing to instead look at what the current\nbackend's xmin is? Seems like you could just replace\n *oldestXmin = XidFromFullTransactionId(ReadNextFullTransactionId());\nwith\n *oldestXmin = MyProc->xmin;\n Assert(TransactionIdIsValid(*oldestXmin));\n\nand you'd not need to care about whether the CLUSTER is top-level or\nnot? Without, I think, loosing any aggressiveness in the top-level case?\nPerhaps even worth moving this logic into\nGetOldestNonRemovableTransactionId().\n\nI know you already pushed this, but I vote for revising it this way if\nyou don't see an issue?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 8 Sep 2020 12:01:29 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: More aggressive vacuuming of temporary tables" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> But now I do wonder why we need to know whether the command is top level\n> or not? Why isn't the correct thing to instead look at what the current\n> backend's xmin is? Seems like you could just replace\n> *oldestXmin = XidFromFullTransactionId(ReadNextFullTransactionId());\n> with\n> *oldestXmin = MyProc->xmin;\n> Assert(TransactionIdIsValid(*oldestXmin));\n\nUmmm ... since VACUUM doesn't run inside a transaction, it won't be\nadvertising an xmin will it?\n\nMaybe you could make something like this work, but I think it'd still\nhave to treat CLUSTER as a special case. Not sure it's worth it.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 08 Sep 2020 15:24:54 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: More aggressive vacuuming of temporary tables" }, { "msg_contents": "Hi,\n\nOn 2020-09-08 15:24:54 -0400, Tom Lane wrote:\n> Andres Freund <andres@anarazel.de> writes:\n> > But now I do wonder why we need to know whether the command is top level\n> > or not? Why isn't the correct thing to instead look at what the current\n> > backend's xmin is? Seems like you could just replace\n> > *oldestXmin = XidFromFullTransactionId(ReadNextFullTransactionId());\n> > with\n> > *oldestXmin = MyProc->xmin;\n> > Assert(TransactionIdIsValid(*oldestXmin));\n> \n> Ummm ... since VACUUM doesn't run inside a transaction, it won't be\n> advertising an xmin will it?\n\nWe do run it in a transaction though:\n\nstatic bool\nvacuum_rel(Oid relid, RangeVar *relation, VacuumParams *params)\n{\n...\n\t/* Begin a transaction for vacuuming this relation */\n\tStartTransactionCommand();\n\n\t/*\n\t * Need to acquire a snapshot to prevent pg_subtrans from being truncated,\n\t * cutoff xids in local memory wrapping around, and to have updated xmin\n\t * horizons.\n\t */\n\tPushActiveSnapshot(GetTransactionSnapshot());\n\n\n> Maybe you could make something like this work, but I think it'd still\n> have to treat CLUSTER as a special case. Not sure it's worth it.\n\nWhy would CLUSTER need to be special cased? We'd precisely retain the\nrows we need to, I think? Given that we'd exactly use the snapshot that\nrules that determines which rows need to be retained?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 8 Sep 2020 14:47:53 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: More aggressive vacuuming of temporary tables" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On 2020-09-08 15:24:54 -0400, Tom Lane wrote:\n>> Andres Freund <andres@anarazel.de> writes:\n>>> But now I do wonder why we need to know whether the command is top level\n>>> or not? Why isn't the correct thing to instead look at what the current\n>>> backend's xmin is? Seems like you could just replace\n>>> *oldestXmin = XidFromFullTransactionId(ReadNextFullTransactionId());\n>>> with\n>>> *oldestXmin = MyProc->xmin;\n>>> Assert(TransactionIdIsValid(*oldestXmin));\n\n>> Ummm ... since VACUUM doesn't run inside a transaction, it won't be\n>> advertising an xmin will it?\n\n> We do run it in a transaction though:\n\nAh. But still, this is not the semantics I want for VACUUM, because the\nprocess xmin will involve other processes' behavior. The point of the\nchange as far as I'm concerned is to ensure vacuuming of dead temp rows\nindependent of anything else in the system.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 08 Sep 2020 18:13:58 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: More aggressive vacuuming of temporary tables" }, { "msg_contents": "Greetings,\n\n* Andres Freund (andres@anarazel.de) wrote:\n> On 2020-08-28 11:46:49 -0400, Tom Lane wrote:\n> > It strikes me that when we are vacuuming a temporary table (which\n> > necessarily will be one of our own session), we don't really need\n> > to care what the global xmin horizon is. If we're not inside a\n> > user transaction block, then there are no tuples in the table that\n> > could be in-doubt anymore. Neither are there any snapshots in our\n> > session that could see any dead tuples. Nor do we give a fig what\n> > other sessions might think of those tuples. So we could just set\n> > the xmin cutoff as aggressively as possible, which is to say\n> > equal to the nextXid counter. While vacuuming a temp table is\n> > perhaps not something people do very often, I think when they do\n> > do it they would like us to clean out all the dead tuples not just\n> > some.\n> \n> That seems like a good idea.\n\nAgreed.\n\n> I've been toying with a patch that introduces more smarts about when a\n> row is removable, by looking more closely whether a specific row\n> versions are visible (e.g. in the common case of one old snapshot and\n> lots of newer rows). But that's orders of magnitude more complicated. So\n> going for something as simple as this seems like a good idea.\n\nI've wondered about this for a long time- very cool that you've found\ntime to actually work on a patch. A couple of different ideas were\ndiscussed previously about how to do that kind of a check- mind talking\nabout what method you're using, or perhaps just sharing that patch? :)\n\nThe potential of such an improvement is huge.\n\nThanks!\n\nStephen", "msg_date": "Wed, 9 Sep 2020 10:14:04 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: More aggressive vacuuming of temporary tables" }, { "msg_contents": "Hi,\n\nOn 2020-09-09 10:14:04 -0400, Stephen Frost wrote:\n> > I've been toying with a patch that introduces more smarts about when a\n> > row is removable, by looking more closely whether a specific row\n> > versions are visible (e.g. in the common case of one old snapshot and\n> > lots of newer rows). But that's orders of magnitude more complicated. So\n> > going for something as simple as this seems like a good idea.\n> \n> I've wondered about this for a long time- very cool that you've found\n> time to actually work on a patch. A couple of different ideas were\n> discussed previously about how to do that kind of a check- mind talking\n> about what method you're using, or perhaps just sharing that patch? :)\n\nIt's very very early, and it doesn't really work. I basically tried to\njust plug a bit more intelligence into the dead tuple detection (which\nnow can easily store more and incrementally built state with the recent\nchanges for snapshot scalability). Detection that tuples newer than the\nhorizon are dead isn't that complicated - what's hard is not breaking\nthings due to ctid chains lacking intermediate versions. To avoid that\nI had to restrict it to inserted (not updated) tuples that were\nsubsequently deleted. And my heuristic only supported only one old\nsnapshot.\n\nBuilding a bsearchable list of ranges of valid (xmin-xmax] ranges isn't\nthat hard. Some care needs to be taken to make the list non-overlapping,\nbut that's easy enough by just merging entries.\n\nObviously lookup in such a more complicated structure isn't free. Nor is\nbuilding it. So we'd need some heuristics about when to do so. It'd\nprobably be OK to occasionally look at the age of the oldest in-progress\nstatement, to infer the time for old snapshots based on that. And then\nwe could have a GUC that says when it's worth doing more complicated\nlookups.\n\nI don't have a handle on how to deal with the ctid chaining for\nintermediate row versions.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 9 Sep 2020 11:02:05 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: More aggressive vacuuming of temporary tables" }, { "msg_contents": "Hi,\n\nOn 2020-09-08 18:13:58 -0400, Tom Lane wrote:\n> Andres Freund <andres@anarazel.de> writes:\n> > On 2020-09-08 15:24:54 -0400, Tom Lane wrote:\n> >> Andres Freund <andres@anarazel.de> writes:\n> >>> But now I do wonder why we need to know whether the command is top level\n> >>> or not? Why isn't the correct thing to instead look at what the current\n> >>> backend's xmin is? Seems like you could just replace\n> >>> *oldestXmin = XidFromFullTransactionId(ReadNextFullTransactionId());\n> >>> with\n> >>> *oldestXmin = MyProc->xmin;\n> >>> Assert(TransactionIdIsValid(*oldestXmin));\n> \n> >> Ummm ... since VACUUM doesn't run inside a transaction, it won't be\n> >> advertising an xmin will it?\n> \n> > We do run it in a transaction though:\n> \n> Ah. But still, this is not the semantics I want for VACUUM, because the\n> process xmin will involve other processes' behavior. The point of the\n> change as far as I'm concerned is to ensure vacuuming of dead temp rows\n> independent of anything else in the system.\n\nI was thinking about this a bit more, and I think the answer might be to\nuse Min(latestCompletedXid, MyProc->xid). That would, as far as I can\ntell, never miss something vacuumable in a temporary table, doesn't\nrequire to know whether we're running as the top-level command.\n\nThe reason for preferring latestCompletedXid over nextXid is that the\nformer is protected by ProcArrayLock and already accessed in\nGetSnapshotData(), so we can cheaply compute the horizons as part of\npruning.\n\nI think that cannot miss something vacuumable in a temp table for VACUUM\nbecause that would have to have been left over by an already completed\ntransaction (by us, before the VACUUM).\n\nIn addition this allows HOT pruning etc on temp tables to be just as\naggressive as VACUUM is.\n\nI wrote a patch to do so for [1], but it seemed topically more relevant\nhere. Running tests in a loop, no failures after the first few\niterations.\n\nGreetings,\n\nAndres Freund\n\n[1] https://postgr.es/m/20200921212003.wrizvknpkim2whzo%40alap3.anarazel.de\n\n\n", "msg_date": "Wed, 14 Oct 2020 13:31:03 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: More aggressive vacuuming of temporary tables" }, { "msg_contents": "On Wed, Sep 9, 2020 at 11:02 AM Andres Freund <andres@anarazel.de> wrote:\n> Obviously lookup in such a more complicated structure isn't free. Nor is\n> building it. So we'd need some heuristics about when to do so. It'd\n> probably be OK to occasionally look at the age of the oldest in-progress\n> statement, to infer the time for old snapshots based on that. And then\n> we could have a GUC that says when it's worth doing more complicated\n> lookups.\n>\n> I don't have a handle on how to deal with the ctid chaining for\n> intermediate row versions.\n\nI wonder if it makes sense to add the feature to nbtree first. This\nside-steps the practical problem of having to figure out ctid\nchaining. You can prove the idea in a relatively low risk way, while\nstill creating significant value for users.\n\nWe can reason about versioning within indexes without having\nauthoritative information about it close at hand. The trick is to\ndelay everything until it looks like we'll have to split the page. I\ncan see very substantial improvements to index bloat from non-HOT\nupdates with the deduplication-deletion patch I've been working on:\n\nhttps://postgr.es/m/CAH2-WznjQQwSPSxBiZ6wQyBiKqFmfdjOdeqp28otqw551T7jcQ@mail.gmail.com\n\nImportantly, the patch tends to bound the number of distinct index\nentries *per logical row* in the presence of non-HOT updates (at least\nfor indexes that are not logically modified by the update). ISTM that\nthis is what really matters. The patch doesn't just reduce index bloat\n-- it greatly caps the number of heap pages any given primary key\npoint lookup query will do. So in practice we eagerly kill precisely\nthe garbage index tuples that would have caused us the most trouble\nwithout the new mechanism in place.\n\nAvoiding a page split is a big win, so we can probably justify\nrelatively expensive lookup calls to make this work. This seems\nespecially likely to be true because we can probably ratchet up to\nthat only when we see that it will win. If a unique index has 10\nentries for one value (10 versions), which is inevitable once HOT\npruning fails, then how many of those 10 do we really need? The answer\nis perhaps just 2 or 3 maybe 99%+ of the time. I strongly suspect that\npreventing page splits is more valuable than opportunistic heap\npruning (unless the pruning itself prevents page splits, which it may\nor may not). Logically unnecessary page splits have obvious lasting\nconsequences, are usually highly correlated, and affect performance in\nways that are non-linear and likely very harmful in the real world.\n\n--\nPeter Geoghegan\n\n\n", "msg_date": "Fri, 16 Oct 2020 12:32:53 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: More aggressive vacuuming of temporary tables" }, { "msg_contents": "Hi,\n\nOn 2020-10-14 13:31:03 -0700, Andres Freund wrote:\n> I was thinking about this a bit more, and I think the answer might be to\n> use Min(latestCompletedXid, MyProc->xid). That would, as far as I can\n> tell, never miss something vacuumable in a temporary table, doesn't\n> require to know whether we're running as the top-level command.\n> \n> The reason for preferring latestCompletedXid over nextXid is that the\n> former is protected by ProcArrayLock and already accessed in\n> GetSnapshotData(), so we can cheaply compute the horizons as part of\n> pruning.\n> \n> I think that cannot miss something vacuumable in a temp table for VACUUM\n> because that would have to have been left over by an already completed\n> transaction (by us, before the VACUUM).\n> \n> In addition this allows HOT pruning etc on temp tables to be just as\n> aggressive as VACUUM is.\n> \n> I wrote a patch to do so for [1], but it seemed topically more relevant\n> here. Running tests in a loop, no failures after the first few\n> iterations.\n> \n> [1] https://postgr.es/m/20200921212003.wrizvknpkim2whzo%40alap3.anarazel.de\n\nPushed this change in logic. The only \"real\" change is that the horizon\nfor backends without an xid needs to be latestCompletedXid + 1, rather\nthan just latestCompletedXid. The horizon indicates the oldest\n*non*-removable xid, and for temp tables latestCompletedXid can always\nbe vacuumed when no xid is assigned.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 28 Oct 2020 18:11:47 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: More aggressive vacuuming of temporary tables" } ]
[ { "msg_contents": "(Forking this thread from the SLRU fsync one[1] to allow for a\nseparate CF entry; it's unrelated, except for being another case of\nmoving work off the recovery process's plate.)\n\nHello hackers,\n\nCurrently we don't run the bgwriter process during crash recovery.\nI've CCed Simon and Heikki who established this in commit cdd46c76.\nBased on that commit message, I think the bar to clear to change the\npolicy is to show that it's useful, and that it doesn't make crash\nrecovery less robust. See the other thread for some initial evidence\nof usefulness from Jakub Wartak. I think it also just makes intuitive\nsense that it's got to help bigger-than-buffer-pool crash recovery if\nyou can shift buffer eviction out of the recovery loop. As for\nrobustness, I suppose we could provide the option to turn it off just\nin case that turns out to be useful in some scenarios, but I'm\nwondering why we would expect something that we routinely run in\narchive/streaming recovery to reduce robustness in only slightly\ndifferent circumstances.\n\nHere's an experiment-grade patch, comments welcome, though at this\nstage it's primarily thoughts about the concept that I'm hoping to\nsolicit.\n\nOne question raised by Jakub that I don't have a great answer to right\nnow is whether you'd want different bgwriter settings in this scenario\nfor best results. I don't know, but I suspect that the answer is to\nmake bgwriter more adaptive rather than more configurable, and that's\nan orthogonal project.\n\nOnce we had the checkpointer running, we could also consider making\nthe end-of-recovery checkpoint optional, or at least the wait for it\nto complete. I haven't shown that in this patch, but it's just\ndifferent checkpoint request flags and possibly an end-of-recovery\nrecord. What problems do you foresee with that? Why should we have\n\"fast\" promotion but not \"fast\" crash recovery?\n\n[1] https://www.postgresql.org/message-id/flat/CA+hUKGLJ=84YT+NvhkEEDAuUtVHMfQ9i-N7k_o50JmQ6Rpj_OQ@mail.gmail.com", "msg_date": "Sun, 30 Aug 2020 12:12:15 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Background writer and checkpointer in crash recovery" }, { "msg_contents": "Thomas Munro <thomas.munro@gmail.com> writes:\n> Once we had the checkpointer running, we could also consider making\n> the end-of-recovery checkpoint optional, or at least the wait for it\n> to complete. I haven't shown that in this patch, but it's just\n> different checkpoint request flags and possibly an end-of-recovery\n> record. What problems do you foresee with that? Why should we have\n> \"fast\" promotion but not \"fast\" crash recovery?\n\nI think that the rationale for that had something to do with trying\nto reduce the costs of repeated crashes. If you've had one crash,\nyou might well have another one in your near future, due to the same\nproblem recurring. Therefore, avoiding multiple replays of the same WAL\nis attractive; and to do that we have to complete a checkpoint before\ngiving users a chance to crash us again.\n\nI'm not sure what I think about your primary proposal here. On the\none hand, optimizing crash recovery ought to be pretty darn far down\nour priority list; if it happens often enough for performance to be\na consideration then we have worse problems to fix. Also, at least\nin theory, not running the bgwriter/checkpointer makes for fewer moving\nparts and thus better odds of completing crash recovery successfully.\nOn the other hand, it could be argued that running without the\nbgwriter/checkpointer actually makes recovery less reliable, since\nthat's a far less thoroughly-tested operating regime than when they're\nactive.\n\ntl;dr: I think this should be much less about performance than about\nwhether we successfully recover or not. Maybe there's still a case for\nchanging in that framework, though.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 29 Aug 2020 20:39:08 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "On Sun, 30 Aug 2020 at 01:39, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Thomas Munro <thomas.munro@gmail.com> writes:\n> > Once we had the checkpointer running, we could also consider making\n> > the end-of-recovery checkpoint optional, or at least the wait for it\n> > to complete. I haven't shown that in this patch, but it's just\n> > different checkpoint request flags and possibly an end-of-recovery\n> > record. What problems do you foresee with that? Why should we have\n> > \"fast\" promotion but not \"fast\" crash recovery?\n>\n> I think that the rationale for that had something to do with trying\n> to reduce the costs of repeated crashes. If you've had one crash,\n> you might well have another one in your near future, due to the same\n> problem recurring. Therefore, avoiding multiple replays of the same WAL\n> is attractive; and to do that we have to complete a checkpoint before\n> giving users a chance to crash us again.\n\nAgreed. That rationale is shown in comments and in the commit message.\n\n\"We could launch it during crash recovery as well, but it seems better to keep\nthat codepath as simple as possible, for the sake of robustness. And it\ncouldn't do any restartpoints during crash recovery anyway, so it wouldn't be\nthat useful.\"\n\nHaving said that, we did raise the checkpoint_timeout by a lot, so the\nsituation today might be quite different. A large checkpoint_timeout\ncould eventually overflow shared buffers, with the right workload.\n\nWe don't have any stats to show whether this patch is worthwhile or\nnot, so I suggest adding the attached instrumentation patch as well so\nwe can see on production systems whether checkpoint_timeout is too\nhigh by comparison with pg_stat_bgwriter. The patch is written in the\nstyle of log_checkpoints.\n\n-- \nSimon Riggs http://www.EnterpriseDB.com/", "msg_date": "Wed, 11 Nov 2020 08:57:15 +0000", "msg_from": "Simon Riggs <simon@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "On Wed, Nov 11, 2020 at 9:57 PM Simon Riggs <simon@2ndquadrant.com> wrote:\n> Having said that, we did raise the checkpoint_timeout by a lot, so the\n> situation today might be quite different. A large checkpoint_timeout\n> could eventually overflow shared buffers, with the right workload.\n\nFWIW Jakuk Wartak did manage to show a 1.64x speedup while running\ncrash recovery of an insert-only workload (with a variant of this\npatch that I shared in another thread), albeit with aggressive tuning:\n\nhttps://www.postgresql.org/message-id/VI1PR0701MB6960EEB838D53886D8A180E3F6520%40VI1PR0701MB6960.eurprd07.prod.outlook.com\n\n> We don't have any stats to show whether this patch is worthwhile or\n> not, so I suggest adding the attached instrumentation patch as well so\n> we can see on production systems whether checkpoint_timeout is too\n> high by comparison with pg_stat_bgwriter. The patch is written in the\n> style of log_checkpoints.\n\nVery useful. I've also been wondering how to get that sort of\ninformation in hot standby.\n\n\n", "msg_date": "Thu, 12 Nov 2020 17:26:39 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "On Sat, Aug 29, 2020 at 8:13 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> Currently we don't run the bgwriter process during crash recovery.\n> I've CCed Simon and Heikki who established this in commit cdd46c76.\n> Based on that commit message, I think the bar to clear to change the\n> policy is to show that it's useful, and that it doesn't make crash\n> recovery less robust. See the other thread for some initial evidence\n> of usefulness from Jakub Wartak. I think it also just makes intuitive\n> sense that it's got to help bigger-than-buffer-pool crash recovery if\n> you can shift buffer eviction out of the recovery loop. As for\n> robustness, I suppose we could provide the option to turn it off just\n> in case that turns out to be useful in some scenarios, but I'm\n> wondering why we would expect something that we routinely run in\n> archive/streaming recovery to reduce robustness in only slightly\n> different circumstances.\n>\n> Here's an experiment-grade patch, comments welcome, though at this\n> stage it's primarily thoughts about the concept that I'm hoping to\n> solicit.\n\nI think the way it works right now is stupid and the proposed change\nis going in the right direction. We have ample evidence already that\nhanding off fsyncs to a background process is a good idea, and there's\nno reason why that shouldn't be beneficial during crash recovery just\nas it is at other times. But even if it somehow failed to improve\nperformance during recovery, there's another good reason to do this,\nwhich is that it would make the code simpler. Having the pendingOps\nstuff in the startup process in some recovery situations and in the\ncheckpointer in other recovery situations makes this harder to reason\nabout. As Tom said, the system state where bgwriter and checkpointer\nare not running is an uncommon one, and is probably more likely to\nhave (or grow) bugs than the state where they are running.\n\nThe rat's-nest of logic introduced by the comment \"Perform a\ncheckpoint to update all our recovery activity to disk.\" inside\nStartupXLOG() could really do with some simplification. Right now we\nhave three cases: CreateEndOfRecoveryRecord(), RequestCheckpoint(),\nand CreateCheckpoint(). Maybe with this change we could get it down to\njust two, since RequestCheckpoint() already knows what to do about\n!IsUnderPostmaster.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 2 Feb 2021 17:11:48 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "On Wed, Feb 3, 2021 at 11:11 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> I think the way it works right now is stupid and the proposed change\n> is going in the right direction. We have ample evidence already that\n> handing off fsyncs to a background process is a good idea, and there's\n> no reason why that shouldn't be beneficial during crash recovery just\n> as it is at other times. But even if it somehow failed to improve\n> performance during recovery, there's another good reason to do this,\n> which is that it would make the code simpler. Having the pendingOps\n> stuff in the startup process in some recovery situations and in the\n> checkpointer in other recovery situations makes this harder to reason\n> about. As Tom said, the system state where bgwriter and checkpointer\n> are not running is an uncommon one, and is probably more likely to\n> have (or grow) bugs than the state where they are running.\n\nYeah, it's a good argument.\n\n> The rat's-nest of logic introduced by the comment \"Perform a\n> checkpoint to update all our recovery activity to disk.\" inside\n> StartupXLOG() could really do with some simplification. Right now we\n> have three cases: CreateEndOfRecoveryRecord(), RequestCheckpoint(),\n> and CreateCheckpoint(). Maybe with this change we could get it down to\n> just two, since RequestCheckpoint() already knows what to do about\n> !IsUnderPostmaster.\n\nTrue. Done in this version.\n\nHere's a rebase of this patch + Simon's patch to report on stats.\n\nI also have a sketch patch to provide a GUC that turns off the\nend-of-recovery checkpoint as mentioned earlier, attached (sharing\nmainly because this is one of the stack of patches that Jakub was\ntesting for his baseback/PITR workloads and he might want to test some\nmore), but I'm not proposing that for PG14. That idea is tangled up\nwith the \"relfile tombstone\" stuff I wrote about elsewhere[1], but I\nhaven't finished studying the full arsenal of footguns in that area\n(it's something like: if we don't wait for end-of-recovery checkpoint\nbefore allowing connections, then we'd better start creating\ntombstones in recovery unless the WAL level is high enough to avoid\ndata eating hazards with unlogged changes and a double crash).\n\n[1] https://commitfest.postgresql.org/33/3030/", "msg_date": "Sat, 13 Mar 2021 11:16:00 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "The following review has been posted through the commitfest application:\nmake installcheck-world: tested, passed\nImplements feature: tested, passed\nSpec compliant: tested, passed\nDocumentation: tested, passed\n\nv2-0001 and v2-0002 look fine, but I don't like much the idea of introducing a new GUC in v2-0003. It's for very specific needs, which most of the users, I believe, don't care about. I suggest dealing with v2-0001 and v2-0002 first and then maybe submit and discuss v2-0003 as a separate CF entry.\r\n\r\nTested on MacOS against master `1ec7fca8`.\n\nThe new status of this patch is: Ready for Committer\n", "msg_date": "Fri, 30 Jul 2021 08:41:41 +0000", "msg_from": "Aleksander Alekseev <aleksander@timescale.com>", "msg_from_op": false, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "On Fri, Jul 30, 2021 at 4:42 AM Aleksander Alekseev\n<aleksander@timescale.com> wrote:\n> v2-0001 and v2-0002 look fine, but I don't like much the idea of introducing a new GUC in v2-0003. It's for very specific needs, which most of the users, I believe, don't care about. I suggest dealing with v2-0001 and v2-0002 first and then maybe submit and discuss v2-0003 as a separate CF entry.\n\nHi!\n\nThanks for bumping this thread; I had forgotten all about this effort,\nbut having just spent a bunch of time struggling with the thicket of\ncases in StartupXLOG(), I'm now feeling highly motivated to make some\nmore progress in simplifying things over there. I am still of the\nopinion that 0001 is a good idea, and I don't have any suggestions for\nhow it could be improved, except perhaps that the call to\nPublishStartupProcessInformation() could maybe have a one-line\ncomment. Thomas, are you planning to press forward with committing\nthis soon? If not, do you mind if I do?\n\nRegarding Simon's 0002, I wonder why it's useful to print this\ninformation out at the end of crash recovery but not at the end of\narchive recovery. It seems to me that if the information is useful\nenough to be worth printing, it's probably good to print it in both\ncases. In fact, rather than adding a separate message for this\ninformation, I think we should just change the existing \"redo done at\"\nmessage to print the details Simon proposes rather than what it does\nnow. Currently, we get output like this:\n\n2021-07-30 09:13:05.319 EDT [48380] LOG: redo starts at 0/23A6E18\n2021-07-30 09:13:05.612 EDT [48380] LOG: redo done at 0/D0D9CE8\nsystem usage: CPU: user: 0.13 s, system: 0.12 s, elapsed: 0.29 s\n\nWith Simon's patch, I get something like this:\n\n2021-07-30 09:39:43.579 EDT [63702] LOG: redo starts at 0/14A2F48\n2021-07-30 09:39:44.129 EDT [63702] LOG: redo done at 0/15F48230\nsystem usage: CPU: user: 0.25 s, system: 0.25 s, elapsed: 0.55 s\n2021-07-30 09:39:44.129 EDT [63702] LOG: crash recovery complete:\nwrote 36517 buffers (222.9%); dirtied 52985 buffers; read 7 buffers\n\nNow I really think that information on the number of buffers touched\nand how long it took is way more useful than user and system time.\nKnowing how much user and system time were spent doesn't really tell\nyou anything, but a count of buffers touched gives you some meaningful\nidea of how much work recovery did, and whether I/O was slow. Elapsed\ntime you can figure out yourself from the timestamp. However, I don't\nreally like printing the percentage here; unlike the checkpoint case,\nit can very easily be way more than a hundred percent, and I think\nthat will confuse people. It could be tens of thousands of percent,\nreally, or even more.\n\nSo my proposal is:\n\nredo done at %X/%X: wrote %ld buffers (%0.3f ms); dirtied %ld buffers;\nread %ld buffers (%0.3f ms)\n\nRegarding 0003, I agree with Alexander's comment that a GUC doesn't\nseem particularly appropriate, but I also think that the approach may\nnot be quite right. In the promotion case, we emit an end-of-recovery\nrecord and then later in the code we trigger a checkpoint. In your\npatch, there's no end-of-recovery checkpoint -- you just trigger a\ncheckpoint instead of waiting for it. I think it's probably better to\nmake those two cases work the same. The end-of-recovery record isn't\nneeded to change the TLI as it is in the promotion case, but (1) it\nseems better to have fewer code paths and (2) it might be good for\ndebuggability.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 30 Jul 2021 10:16:44 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "Hi,\n\nOn 2021-07-30 10:16:44 -0400, Robert Haas wrote:\n> 2021-07-30 09:39:43.579 EDT [63702] LOG: redo starts at 0/14A2F48\n> 2021-07-30 09:39:44.129 EDT [63702] LOG: redo done at 0/15F48230\n> system usage: CPU: user: 0.25 s, system: 0.25 s, elapsed: 0.55 s\n> 2021-07-30 09:39:44.129 EDT [63702] LOG: crash recovery complete:\n> wrote 36517 buffers (222.9%); dirtied 52985 buffers; read 7 buffers\n> \n> Now I really think that information on the number of buffers touched\n> and how long it took is way more useful than user and system time.\n> Knowing how much user and system time were spent doesn't really tell\n> you anything, but a count of buffers touched gives you some meaningful\n> idea of how much work recovery did, and whether I/O was slow.\n\nI don't agree with that? If (user+system) << wall then it is very likely\nthat recovery is IO bound. If system is a large percentage of wall, then\nshared buffers is likely too small (or we're replacing the wrong\nbuffers) because you spend a lot of time copying data in/out of the\nkernel page cache. If user is the majority, you're CPU bound.\n\nWithout user & system time it's much harder to figure that out - at\nleast for me.\n\n\n> In your patch, there's no end-of-recovery checkpoint -- you just\n> trigger a checkpoint instead of waiting for it. I think it's probably\n> better to make those two cases work the same. The end-of-recovery\n> record isn't needed to change the TLI as it is in the promotion case,\n> but (1) it seems better to have fewer code paths and (2) it might be\n> good for debuggability.\n\n+1\n\nIn addition, the end-of-recovery record also good for e.g. hot standby,\nlogical decoding, etc, because it's a point where no write transactions\ncan be in progress...\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 30 Jul 2021 13:00:44 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "On Sat, Jul 31, 2021 at 2:16 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> On Fri, Jul 30, 2021 at 4:42 AM Aleksander Alekseev\n> <aleksander@timescale.com> wrote:\n> > v2-0001 and v2-0002 look fine, but I don't like much the idea of introducing a new GUC in v2-0003. It's for very specific needs, which most of the users, I believe, don't care about. I suggest dealing with v2-0001 and v2-0002 first and then maybe submit and discuss v2-0003 as a separate CF entry.\n\nThanks.\n\n> Thanks for bumping this thread; I had forgotten all about this effort,\n> but having just spent a bunch of time struggling with the thicket of\n> cases in StartupXLOG(), I'm now feeling highly motivated to make some\n> more progress in simplifying things over there. I am still of the\n> opinion that 0001 is a good idea, and I don't have any suggestions for\n> how it could be improved,\n\nThat's good news, and thanks. Yes, clearly there is much more that\ncan be simplified here.\n\n> except perhaps that the call to\n> PublishStartupProcessInformation() could maybe have a one-line\n> comment.\n\nDone. BTW that is temporary, as I'm planning to remove that machinery soon[1].\n\n> Thomas, are you planning to press forward with committing\n> this soon? If not, do you mind if I do?\n\nI pushed 0001. Let me think about 0002, and flesh out 0003 a bit more.\n\n[1] https://www.postgresql.org/message-id/flat/CA+hUKGLYRyDaneEwz5Uya_OgFLMx5BgJfkQSD=q9HmwsfRRb-w@mail.gmail.com\n\n\n", "msg_date": "Mon, 2 Aug 2021 17:36:23 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "On Fri, Jul 30, 2021 at 4:00 PM Andres Freund <andres@anarazel.de> wrote:\n> I don't agree with that? If (user+system) << wall then it is very likely\n> that recovery is IO bound. If system is a large percentage of wall, then\n> shared buffers is likely too small (or we're replacing the wrong\n> buffers) because you spend a lot of time copying data in/out of the\n> kernel page cache. If user is the majority, you're CPU bound.\n>\n> Without user & system time it's much harder to figure that out - at\n> least for me.\n\nOh, that's an interesting point. At least now I'll know why I am\nsupposed to care about that log line the next time I see it. I guess\nwe could include both things, though the line might get a little long.\nOr maybe there's some other subset that would make sense.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 2 Aug 2021 09:07:18 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "On Mon, Aug 2, 2021 at 1:37 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n> I pushed 0001.\n\nThat's great. I just realized that this leaves us with identical\nRequestCheckpoint() calls in two nearby places. Is there any reason\nnot to further simplify as in the attached?\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com", "msg_date": "Mon, 2 Aug 2021 09:17:29 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "On Mon, Aug 2, 2021 at 6:47 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n> On Mon, Aug 2, 2021 at 1:37 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n> > I pushed 0001.\n>\n> That's great. I just realized that this leaves us with identical\n> RequestCheckpoint() calls in two nearby places. Is there any reason\n> not to further simplify as in the attached?\n>\n+1, also, can we just get rid off \"promoted\" flag? The only\ninconvenience is we might need to check three flags instead of one to\nperform the checkpoint at the end.\n\n\n", "msg_date": "Mon, 2 Aug 2021 19:10:20 +0530", "msg_from": "Amul Sul <sulamul@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "> On Fri, Jul 30, 2021 at 4:00 PM Andres Freund <andres@anarazel.de> wrote:\n> > I don't agree with that? If (user+system) << wall then it is very\n> > likely that recovery is IO bound. If system is a large percentage of\n> > wall, then shared buffers is likely too small (or we're replacing the\n> > wrong\n> > buffers) because you spend a lot of time copying data in/out of the\n> > kernel page cache. If user is the majority, you're CPU bound.\n> >\n> > Without user & system time it's much harder to figure that out - at\n> > least for me.\n> \n> Oh, that's an interesting point. At least now I'll know why I am supposed to care\n> about that log line the next time I see it. I guess we could include both things,\n> though the line might get a little long.\n> Or maybe there's some other subset that would make sense.\n\nHi Robert,\n\nThe email threads from [1] can serve as indication that having complete view of \nresource usage (user+system+elapsed) is advantageous in different situations and \npretty platform-generic. Also as Andres and Simon earlier pointed out - the performance\ninsight into crash recovery/replication performance is next to nothing, judging just by \nlooking at currently emitted log messages. The more the there is, the better I think. \n\nBTW, if you now there's this big push for refactoring StartupXLOG() then what \nfrustrating^H^H^H^H^H could be done better - at least from end-user point of view - \nis that there is lack of near real time cyclic messages (every 1min?) about current status, \nperformance and maybe even ETA (simplistic case; assuming it is linear). \n\n[1] - https://commitfest.postgresql.org/30/2799/ \n\n\n", "msg_date": "Mon, 2 Aug 2021 13:51:44 +0000", "msg_from": "Jakub Wartak <Jakub.Wartak@tomtom.com>", "msg_from_op": false, "msg_subject": "RE: Background writer and checkpointer in crash recovery" }, { "msg_contents": "On Mon, Aug 2, 2021 at 9:40 AM Amul Sul <sulamul@gmail.com> wrote:\n> > That's great. I just realized that this leaves us with identical\n> > RequestCheckpoint() calls in two nearby places. Is there any reason\n> > not to further simplify as in the attached?\n> >\n> +1, also, can we just get rid off \"promoted\" flag? The only\n> inconvenience is we might need to check three flags instead of one to\n> perform the checkpoint at the end.\n\nI'm not sure that's really a win, because if we use the same\nconditional in both places then it might not be clear to somebody that\nthey're supposed to match.\n\nI do think we ought to consider renaming the flag, though, because\nLocalPromoteIsTriggered is already tracking whether we were promoted,\nand what this flag is tracking is not quite that thing. It's real\npurpose is to track whether we should request a non-immediate\ncheckpoint at the end of recovery, and I think we ought to name it\nsome way that reflects that, e.g. perform_checkpoint_later.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 2 Aug 2021 10:47:06 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "On Mon, Aug 2, 2021 at 9:51 AM Jakub Wartak <Jakub.Wartak@tomtom.com> wrote:\n> BTW, if you now there's this big push for refactoring StartupXLOG() then what\n> frustrating^H^H^H^H^H could be done better - at least from end-user point of view -\n> is that there is lack of near real time cyclic messages (every 1min?) about current status,\n> performance and maybe even ETA (simplistic case; assuming it is linear).\n\nI agree. See https://www.postgresql.org/message-id/CA+TgmoaHQrgDFOBwgY16XCoMtXxsrVGFB2jNCvb7-ubuEe1MGg@mail.gmail.com\nand subsequent discussion.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 2 Aug 2021 10:48:08 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "On Tue, Aug 3, 2021 at 1:17 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> That's great. I just realized that this leaves us with identical\n> RequestCheckpoint() calls in two nearby places. Is there any reason\n> not to further simplify as in the attached?\n\nLGTM.\n\n\n", "msg_date": "Tue, 3 Aug 2021 09:52:37 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "On Tue, Aug 3, 2021 at 9:52 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n> On Tue, Aug 3, 2021 at 1:17 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> > That's great. I just realized that this leaves us with identical\n> > RequestCheckpoint() calls in two nearby places. Is there any reason\n> > not to further simplify as in the attached?\n>\n> LGTM.\n\nAnd pushed.\n\n\n", "msg_date": "Tue, 3 Aug 2021 14:19:22 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "On Tue, Aug 03, 2021 at 02:19:22PM +1200, Thomas Munro wrote:\n> On Tue, Aug 3, 2021 at 9:52 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n> > On Tue, Aug 3, 2021 at 1:17 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> > > That's great. I just realized that this leaves us with identical\n> > > RequestCheckpoint() calls in two nearby places. Is there any reason\n> > > not to further simplify as in the attached?\n> >\n> > LGTM.\n> \n> And pushed.\n\nGripe: this made the \"ps\" display worse than before.\n\n7ff23c6d2 Run checkpointer and bgwriter in crash recovery.\n\nA couple years ago, I complained that during the end-of-recovery\ncheckpoint, the \"ps\" display still said \"recovering NNNNN\", which made\nit look like it was stuck on a particular WAL file.\n\nThat led to commit df9274adf, which updated the startup process's \"ps\"\nto say \"end-of-recovery checkpoint\".\n\nBut since the start process no longer does the checkpoint, it still\nsays:\n\npostgres 19738 11433 5 19:33 ? 00:00:01 postgres: startup recovering 000000010000000C000000FB\npostgres 19739 11433 3 19:33 ? 00:00:00 postgres: checkpointer performing end-of-recovery checkpoint\n\nThat looks inconsistent. It'd be better if the startup process's \"ps\"\nwere cleared.\n\n-- \nJustin\n\n\n", "msg_date": "Sun, 11 Sep 2022 19:54:43 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "On Sun, Sep 11, 2022 at 07:54:43PM -0500, Justin Pryzby wrote:\n> On Tue, Aug 03, 2021 at 02:19:22PM +1200, Thomas Munro wrote:\n> > On Tue, Aug 3, 2021 at 9:52 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n> > > On Tue, Aug 3, 2021 at 1:17 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> > > > That's great. I just realized that this leaves us with identical\n> > > > RequestCheckpoint() calls in two nearby places. Is there any reason\n> > > > not to further simplify as in the attached?\n> > >\n> > > LGTM.\n> > \n> > And pushed.\n> \n> Gripe: this made the \"ps\" display worse than before.\n> \n> 7ff23c6d2 Run checkpointer and bgwriter in crash recovery.\n> \n> A couple years ago, I complained that during the end-of-recovery\n> checkpoint, the \"ps\" display still said \"recovering NNNNN\", which made\n> it look like it was stuck on a particular WAL file.\n> \n> That led to commit df9274adf, which updated the startup process's \"ps\"\n> to say \"end-of-recovery checkpoint\".\n> \n> But since the start process no longer does the checkpoint, it still\n> says:\n> \n> postgres 19738 11433 5 19:33 ? 00:00:01 postgres: startup recovering 000000010000000C000000FB\n> postgres 19739 11433 3 19:33 ? 00:00:00 postgres: checkpointer performing end-of-recovery checkpoint\n> \n> That looks inconsistent. It'd be better if the startup process's \"ps\"\n> were cleared.\n\nLike this, maybe.\n\nIt's similar to what I suggested to consider backpatching here:\nhttps://www.postgresql.org/message-id/20201214032224.GA30237%40telsasoft.com\n\ndiff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c\nindex 7a710e6490d..4bf8614d45f 100644\n--- a/src/backend/access/transam/xlog.c\n+++ b/src/backend/access/transam/xlog.c\n@@ -5302,6 +5302,7 @@ StartupXLOG(void)\n \tEndOfLogTLI = endOfRecoveryInfo->endOfLogTLI;\n \tabortedRecPtr = endOfRecoveryInfo->abortedRecPtr;\n \tmissingContrecPtr = endOfRecoveryInfo->missingContrecPtr;\n+\tset_ps_display(\"\");\n \n \t/*\n \t * When recovering from a backup (we are in recovery, and archive recovery\n\n\n", "msg_date": "Mon, 12 Sep 2022 21:13:11 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "On Mon, Sep 12, 2022 at 09:13:11PM -0500, Justin Pryzby wrote:\n> Like this, maybe.\n> \n> It's similar to what I suggested to consider backpatching here:\n> https://www.postgresql.org/message-id/20201214032224.GA30237%40telsasoft.com\n\nAt the same time, df9274adf has been done because the end-of-recovery\ncheckpoint done potentially by the startup process if the checkpointer\nwas not up at the end of recovery would take long. Any of the actions\ntaken in the startup process when finishing recovery are not that\ncostly, on the contrary, as far as I know.\n\nI am not opposed to clearing the ps display when we are at this state\nof the game for the startup process, but rather than clearing it we\ncould switch provide something more useful that shows what's\nhappening. Say a simple \"performing end-of-recovery actions\", for\nexample..\n--\nMichael", "msg_date": "Tue, 13 Sep 2022 13:32:11 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "On Tue, Sep 13, 2022 at 01:32:11PM +0900, Michael Paquier wrote:\n> On Mon, Sep 12, 2022 at 09:13:11PM -0500, Justin Pryzby wrote:\n> > Like this, maybe.\n> > \n> > It's similar to what I suggested to consider backpatching here:\n> > https://www.postgresql.org/message-id/20201214032224.GA30237%40telsasoft.com\n> \n> At the same time, df9274adf has been done because the end-of-recovery\n> checkpoint done potentially by the startup process if the checkpointer\n> was not up at the end of recovery would take long. Any of the actions\n> taken in the startup process when finishing recovery are not that\n> costly, on the contrary, as far as I know.\n\nYour interpretation may be a bit different from mine.\n\nThe central problem for me was that the startup process said \"recovering\nNNN\" after it was done recovering NNN.\n\nTo fix that, df9274adf took the approach of overwriting the existing PS\nwith \"end-of-recovery checkpoint\", which also adds some extra value...\n\n> I am not opposed to clearing the ps display when we are at this state\n> of the game for the startup process, but rather than clearing it we\n> could switch provide something more useful that shows what's\n> happening. Say a simple \"performing end-of-recovery actions\", for\n> example..\n\n...but the minimal solution (which 2 years ago I suggested could've been\nbackpatched) is to *clear* the PS (in master branch at the time, that\nwould've been before also changing it to say stuff about the\ncheckpoint).\n\nIf we'd done that, I probably wouldn't be griping about it now, so my\npreference is to *clear* the display as soon as the WAL processing is\ndone; further overwriting it with additional stuff can be left as a\nfuture enhancement (like \"syncing FS\" that I brought up last year, and\nmaybe everything else that calls ereport_startup_progress()).\n\n\n", "msg_date": "Tue, 13 Sep 2022 17:39:55 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "I don't know that this warrants an Opened Item, but I think some fix\nought to be applied to v15, whether that happens this week or next\nmonth.\n\n\n", "msg_date": "Thu, 15 Sep 2022 22:19:01 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Background writer and checkpointer in crash recovery" }, { "msg_contents": "On Thu, Sep 15, 2022 at 10:19:01PM -0500, Justin Pryzby wrote:\n> I don't know that this warrants an Opened Item, but I think some fix\n> ought to be applied to v15, whether that happens this week or next\n> month.\n\nWith RC1 getting close by, I have looked at that again and applied a\npatch that resets the ps display after recovery is done, bringing as\nback to the same state as PG <= 14 in the startup process.\n--\nMichael", "msg_date": "Thu, 22 Sep 2022 14:33:57 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Background writer and checkpointer in crash recovery" } ]
[ { "msg_contents": "Hi,\n\nA couple of recent cases where an error \"libpq is incorrectly linked\nto backend functions\" broke the dblink test:\n\n https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=lorikeet&dt=2020-08-22%2002:55:22\n | REL9_6_STABLE | Windows\n https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=lorikeet&dt=2020-04-27%2022:46:16\n | HEAD | Windows\n\nBefore that, lorikeet last said that before commit a33245a8 apparently\nfixed something relevant, but curiously the message also appeared a\ncouple of times on two Unixen. Perhaps we can write those off as lost\nin the mists of time.\n\n https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=lorikeet&dt=2018-09-29%2010:56:25\n | HEAD | Windows\n https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=damselfly&dt=2018-09-10%2011:09:29\n | HEAD | Illumos\n https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=jaguarundi&dt=2018-09-09%2018:11:15\n| HEAD | FreeBSD\n\n\n", "msg_date": "Sun, 30 Aug 2020 15:51:51 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Rare link canary failure in dblink test" }, { "msg_contents": "Thomas Munro <thomas.munro@gmail.com> writes:\n> A couple of recent cases where an error \"libpq is incorrectly linked\n> to backend functions\" broke the dblink test:\n\nlorikeet seems just plain unstable these days :-(. Don't know why.\n\n> ... curiously the message also appeared a\n> couple of times on two Unixen. Perhaps we can write those off as lost\n> in the mists of time.\n\nNo, those were expected, because they ran between ed0cdf0e0, which\nintentionally introduced this error, and e3d77ea6b and 4fa3741d1\nwhich fixed it.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 30 Aug 2020 10:48:42 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Rare link canary failure in dblink test" } ]
[ { "msg_contents": "Hi all,\n\nIn the current lazy vacuum implementation, some index AMs such as\nbtree indexes call lazy_tid_reaped() for each index tuples during\nambulkdelete to check if the index tuple points to the (collected)\ngarbage tuple. In that function, we simply call bsearch(3) but we\nshould be able to know the result without bsearch(3) if the index\ntuple points to the heap tuple that is out of range of the collected\ngarbage tuples. I've checked whether bsearch(3) does the boundary\nvalue check or not but looking at the bsearch(3) implementation of\nFreeBSD libc[1], there is not. The same is true for glibc.\n\nSo my proposal is to add boundary value check in lazy_tid_reaped()\nbefore executing bsearch(3). This will help when index vacuum happens\nmultiple times or when garbage tuples are concentrated to a narrow\nrange.\n\nI’ve done three performance tests. maintenance_work_mem is set to 64MB\nwith which we can collect about 11 million tuples at maximum and the\ntable size is 10GB. The table has one btree index. Here is the average\nof index vacuum (ambulkdelete) execution time of three trials:\n\n* Test case 1\n\nI made all pages dirty with 15 million garbage tuples to invoke index\nvacuum twice.\n\nHEAD: 164.7 s\nPatched: 138.81 s\n\n* Test case 2\n\nI made all pages dirty with 10 million garbage tuples to invoke index\nvacuum only once, checking the performance degradation.\n\nHEAD: 127.8 s\nPatched: 128.25 s\n\n* Test case 3\n\nI made a certain range of table dirty with 1 million garbage tuples.\n\nHEAD: 31.07 s\nPatched: 9.41 s\n\nI thought that we can have a generic function wrapping bsearch(3) that\ndoes boundary value checks and then does bsearch(3) so that we can use\nit in other similar places as well. But the attached patch doesn't do\nthat as I'd like to hear opinions on the proposal first.\n\nFeedback is very welcome.\n\nRegards,\n\n[1] https://svnweb.freebsd.org/base/head/lib/libc/stdlib/bsearch.c?revision=326025&view=markup\n\n--\nMasahiko Sawada http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Sun, 30 Aug 2020 20:07:38 +0900", "msg_from": "Masahiko Sawada <masahiko.sawada@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Boundary value check in lazy_tid_reaped()" }, { "msg_contents": "On Sun, Aug 30, 2020 at 11:08 PM Masahiko Sawada\n<masahiko.sawada@2ndquadrant.com> wrote:\n> So my proposal is to add boundary value check in lazy_tid_reaped()\n> before executing bsearch(3). This will help when index vacuum happens\n> multiple times or when garbage tuples are concentrated to a narrow\n> range.\n\nMakes sense if it's often out of range.\n\n> I thought that we can have a generic function wrapping bsearch(3) that\n> does boundary value checks and then does bsearch(3) so that we can use\n> it in other similar places as well. But the attached patch doesn't do\n> that as I'd like to hear opinions on the proposal first.\n\nI wonder if you would also see a speed-up with a bsearch() replacement\nthat is inlineable, so it can inline the comparator (instead of\ncalling it through a function pointer). I wonder if something more\nlike (lblk << 32 | loff) - (rblk << 32 | roff) would go faster than\nthe branchy comparator.\n\n\n", "msg_date": "Tue, 1 Sep 2020 07:21:57 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Boundary value check in lazy_tid_reaped()" }, { "msg_contents": "On Tue, Sep 1, 2020 at 7:21 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n> On Sun, Aug 30, 2020 at 11:08 PM Masahiko Sawada\n> <masahiko.sawada@2ndquadrant.com> wrote:\n> > So my proposal is to add boundary value check in lazy_tid_reaped()\n> > before executing bsearch(3). This will help when index vacuum happens\n> > multiple times or when garbage tuples are concentrated to a narrow\n> > range.\n>\n> Makes sense if it's often out of range.\n\n... though I'm not sure why you need to add extra members to do it?\n\n> > I thought that we can have a generic function wrapping bsearch(3) that\n> > does boundary value checks and then does bsearch(3) so that we can use\n> > it in other similar places as well. But the attached patch doesn't do\n> > that as I'd like to hear opinions on the proposal first.\n>\n> I wonder if you would also see a speed-up with a bsearch() replacement\n> that is inlineable, so it can inline the comparator (instead of\n> calling it through a function pointer). I wonder if something more\n> like (lblk << 32 | loff) - (rblk << 32 | roff) would go faster than\n> the branchy comparator.\n\nErm, off course that expression won't work... should be << 16, but\neven then it would only work with a bsearch that uses int64_t\ncomparators, so I take that part back.\n\n\n", "msg_date": "Tue, 1 Sep 2020 07:43:24 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Boundary value check in lazy_tid_reaped()" }, { "msg_contents": "On Mon, Aug 31, 2020 at 12:22 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> On Sun, Aug 30, 2020 at 11:08 PM Masahiko Sawada\n> <masahiko.sawada@2ndquadrant.com> wrote:\n> > So my proposal is to add boundary value check in lazy_tid_reaped()\n> > before executing bsearch(3). This will help when index vacuum happens\n> > multiple times or when garbage tuples are concentrated to a narrow\n> > range.\n>\n> Makes sense if it's often out of range.\n\nI also think this is a good idea. But I also wonder if it goes far\nenough. Only one or two dead TIDs in inconvenient heap pages can\ncompletely defeat the optimization.\n\nA related problem with the TID list is that it is very space\ninefficient. It would be nice to fix that problem at some point. We\ncould make multiple index scans by VACUUM operations much rarer if we\ntried. But how can we do all of this together?\n\nI wonder if Roaring bitmaps would work well for this:\n\nhttps://arxiv.org/abs/1709.07821\n\nThis data structure looks like it might work well in lazy_tid_reaped()\n(for the TID array), because it offers effective bitmap compression\nwithout compromising on binary search speed. Of course, you'd have to\nencode TIDs as bitmaps to make use of the data structure, much like\ntidbitmap.c. I imagine that the Roaring bitmap indirection would be\nvery CPU cache efficient in cases that are similar to the cases\nSawada-san is worried about, but a bit more complicated.\n\nVACUUM would be able to make the summarizing information for the TID\nbitmap resident in CPU cache. Only this well-cached summarizing\ninformation (the top-level bitmap range indirection) will need to be\naccessed by most individual calls to a Roaring-bitmap-aware\nlazy_tid_reaped() that return false (i.e. calls that say \"don't kill\nthis TID, it's alive\"). These performance characteristics seem likely\nwhen a certain amount of clustering of dead tuples takes place in the\nheap. I bet having completely random positions for dead TIDs almost\nnever happens -- *some* clustering is practically certain to take\nplace, even without natural locality in the data (which is itself very\ncommon). Think about how opportunistic pruning accumulates many\nLP_DEAD items in heap pages.\n\nThere is a reference Roaring bitmap implementation in C, so it's\nprobably not that hard to experimentally determine how well it would\nwork:\n\nhttps://github.com/RoaringBitmap/CRoaring\n\nLots of open source projects already use it, so there are no problems\nwith patents. Seems worth investigating. (I also wonder if we could\nuse it for clog.)\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Mon, 31 Aug 2020 13:56:36 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: Boundary value check in lazy_tid_reaped()" }, { "msg_contents": "On Mon, Aug 31, 2020 at 1:56 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> I wonder if Roaring bitmaps would work well for this:\n>\n> https://arxiv.org/abs/1709.07821\n\nAlternatively, perhaps we could use a negative cache of heap blocks\nthat have no tuples to kill at all. Maybe just a simple array whose\nelements are BlockNumber pairs. Each pair represents a range of blocks\nknown to contain heap pages that *don't* have any TIDs for VACUUM to\nkill. The array could be size limited to 8KB, allowing it to be\naccessed in L1 cache throughout vacuuming. When the representation\ncannot fit in 8KB, maybe we disable the negative cache for the rest of\nthe VACUUM operation.\n\nThis is a bit like Masahiko's min_blkno + max_blkno idea, except: 1).\nIt's a negative cache, and 2.) There are perhaps as many as 1024\nmin/max pairs -- not just 1.\n\nIt's pretty clear that more than 90% of all calls to lazy_tid_reaped()\nreturn false unless vacuum is running behind (false means \"don't kill\nthis TID, it's alive\"). But it could be much more than 90%. This may\nbe because autovacuum is configured to run more aggressively than the\ndefault settings allow. But it may also happen when LP_DEAD killing in\nindexes works well enough to do most of the cleanup needed in\npractice. I bet pgbench finds that ~99% of all calls to\nlazy_tid_reaped() that take place during index vacuuming find that the\nTID doesn't need to be killed. So negative caching could really help.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Mon, 31 Aug 2020 16:01:10 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: Boundary value check in lazy_tid_reaped()" }, { "msg_contents": "On Tue, 1 Sep 2020 at 04:44, Thomas Munro <thomas.munro@gmail.com> wrote:\n>\n> On Tue, Sep 1, 2020 at 7:21 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n> > On Sun, Aug 30, 2020 at 11:08 PM Masahiko Sawada\n> > <masahiko.sawada@2ndquadrant.com> wrote:\n> > > So my proposal is to add boundary value check in lazy_tid_reaped()\n> > > before executing bsearch(3). This will help when index vacuum happens\n> > > multiple times or when garbage tuples are concentrated to a narrow\n> > > range.\n> >\n> > Makes sense if it's often out of range.\n>\n> ... though I'm not sure why you need to add extra members to do it?\n\nIndeed. We can use the first and last elements of itemptrs array.\n\n>\n> > > I thought that we can have a generic function wrapping bsearch(3) that\n> > > does boundary value checks and then does bsearch(3) so that we can use\n> > > it in other similar places as well. But the attached patch doesn't do\n> > > that as I'd like to hear opinions on the proposal first.\n> >\n> > I wonder if you would also see a speed-up with a bsearch() replacement\n> > that is inlineable, so it can inline the comparator (instead of\n> > calling it through a function pointer). I wonder if something more\n> > like (lblk << 32 | loff) - (rblk << 32 | roff) would go faster than\n> > the branchy comparator.\n>\n> Erm, off course that expression won't work... should be << 16, but\n> even then it would only work with a bsearch that uses int64_t\n> comparators, so I take that part back.\n\nYeah, it seems to worth benchmarking the speed-up with an inlining.\nI'll do some performance tests with/without inlining on top of\nchecking boundary values.\n\nRegards,\n\n--\nMasahiko Sawada http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 8 Sep 2020 17:23:04 +0900", "msg_from": "Masahiko Sawada <masahiko.sawada@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: Boundary value check in lazy_tid_reaped()" }, { "msg_contents": "On Tue, Sep 8, 2020 at 1:23 AM Masahiko Sawada\n<masahiko.sawada@2ndquadrant.com> wrote:\n> > > I wonder if you would also see a speed-up with a bsearch() replacement\n> > > that is inlineable, so it can inline the comparator (instead of\n> > > calling it through a function pointer). I wonder if something more\n> > > like (lblk << 32 | loff) - (rblk << 32 | roff) would go faster than\n> > > the branchy comparator.\n> >\n> > Erm, off course that expression won't work... should be << 16, but\n> > even then it would only work with a bsearch that uses int64_t\n> > comparators, so I take that part back.\n>\n> Yeah, it seems to worth benchmarking the speed-up with an inlining.\n> I'll do some performance tests with/without inlining on top of\n> checking boundary values.\n\nIt sounds like Thomas was talking about something like\nitemptr_encode() + itemptr_decode(). In case you didn't know, we\nactually do something like this for the TID tuplesort used for CREATE\nINDEX CONCURRENTLY.\n\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Tue, 8 Sep 2020 12:33:32 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: Boundary value check in lazy_tid_reaped()" }, { "msg_contents": "On Tue, 1 Sep 2020 at 08:01, Peter Geoghegan <pg@bowt.ie> wrote:\n>\n> On Mon, Aug 31, 2020 at 1:56 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> > I wonder if Roaring bitmaps would work well for this:\n> >\n> > https://arxiv.org/abs/1709.07821\n>\n> Alternatively, perhaps we could use a negative cache of heap blocks\n> that have no tuples to kill at all. Maybe just a simple array whose\n> elements are BlockNumber pairs. Each pair represents a range of blocks\n> known to contain heap pages that *don't* have any TIDs for VACUUM to\n> kill. The array could be size limited to 8KB, allowing it to be\n> accessed in L1 cache throughout vacuuming. When the representation\n> cannot fit in 8KB, maybe we disable the negative cache for the rest of\n> the VACUUM operation.\n>\n> This is a bit like Masahiko's min_blkno + max_blkno idea, except: 1).\n> It's a negative cache, and 2.) There are perhaps as many as 1024\n> min/max pairs -- not just 1.\n\nInteresting idea. Maybe we need one more bsearch() for the min/max\npairs array when a TID should be killed?\n\n>\n> It's pretty clear that more than 90% of all calls to lazy_tid_reaped()\n> return false unless vacuum is running behind (false means \"don't kill\n> this TID, it's alive\"). But it could be much more than 90%. This may\n> be because autovacuum is configured to run more aggressively than the\n> default settings allow. But it may also happen when LP_DEAD killing in\n> indexes works well enough to do most of the cleanup needed in\n> practice. I bet pgbench finds that ~99% of all calls to\n> lazy_tid_reaped() that take place during index vacuuming find that the\n> TID doesn't need to be killed. So negative caching could really help.\n\nI agree that lazy_tid_reaped() returns false in most checks in the\ncase autovacuum is not running behind. But I'm concerned a bit that it\ninstead costs the case where vacuum needs to kill many TIDs and uses\nthe min/max filter because it needs to call bsearch() twice. I think\nthat this is the case where autovacuum is running behind and the user\nwants to complete the vacuum as soon as possible. Since I expect that\nchecking the filtering using min/max pairs array should be done in a\nvery short time it might not be a problem but I think it’s worth\nbenchmarking the overhead in the worst case. Or I guess we can use a\nbloom filter for this purpose instead.\n\nAlso, I'm concerned that 1024 min/max pairs might not be enough in\npractice, especially for very large tables.\n\nRegards,\n\n--\nMasahiko Sawada http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 10 Sep 2020 22:47:04 +0900", "msg_from": "Masahiko Sawada <masahiko.sawada@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: Boundary value check in lazy_tid_reaped()" }, { "msg_contents": "On Tue, 1 Sep 2020 at 05:56, Peter Geoghegan <pg@bowt.ie> wrote:\n>\n> On Mon, Aug 31, 2020 at 12:22 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> > On Sun, Aug 30, 2020 at 11:08 PM Masahiko Sawada\n> > <masahiko.sawada@2ndquadrant.com> wrote:\n> > > So my proposal is to add boundary value check in lazy_tid_reaped()\n> > > before executing bsearch(3). This will help when index vacuum happens\n> > > multiple times or when garbage tuples are concentrated to a narrow\n> > > range.\n> >\n> > Makes sense if it's often out of range.\n>\n> I also think this is a good idea. But I also wonder if it goes far\n> enough. Only one or two dead TIDs in inconvenient heap pages can\n> completely defeat the optimization.\n>\n> A related problem with the TID list is that it is very space\n> inefficient. It would be nice to fix that problem at some point. We\n> could make multiple index scans by VACUUM operations much rarer if we\n> tried. But how can we do all of this together?\n>\n> I wonder if Roaring bitmaps would work well for this:\n>\n> https://arxiv.org/abs/1709.07821\n>\n> This data structure looks like it might work well in lazy_tid_reaped()\n> (for the TID array), because it offers effective bitmap compression\n> without compromising on binary search speed. Of course, you'd have to\n> encode TIDs as bitmaps to make use of the data structure, much like\n> tidbitmap.c. I imagine that the Roaring bitmap indirection would be\n> very CPU cache efficient in cases that are similar to the cases\n> Sawada-san is worried about, but a bit more complicated.\n>\n> VACUUM would be able to make the summarizing information for the TID\n> bitmap resident in CPU cache. Only this well-cached summarizing\n> information (the top-level bitmap range indirection) will need to be\n> accessed by most individual calls to a Roaring-bitmap-aware\n> lazy_tid_reaped() that return false (i.e. calls that say \"don't kill\n> this TID, it's alive\"). These performance characteristics seem likely\n> when a certain amount of clustering of dead tuples takes place in the\n> heap. I bet having completely random positions for dead TIDs almost\n> never happens -- *some* clustering is practically certain to take\n> place, even without natural locality in the data (which is itself very\n> common). Think about how opportunistic pruning accumulates many\n> LP_DEAD items in heap pages.\n>\n> There is a reference Roaring bitmap implementation in C, so it's\n> probably not that hard to experimentally determine how well it would\n> work:\n>\n> https://github.com/RoaringBitmap/CRoaring\n>\n> Lots of open source projects already use it, so there are no problems\n> with patents. Seems worth investigating. (I also wonder if we could\n> use it for clog.)\n\nVery interesting.\n\nBefore getting into CRoaring bitmap, I've done some experiments with\nthree different methods of recording dead tuple TIDs: array,\narray-minmax, and integer set.\n\n'array' is the current method lazy vacuum uses. It just adds dead\ntuple TIDs to the simple array of ItemPointerData.\n'array-minmax' is the same as 'array' method except for checking min\nand max boundaries when deleting index dead tuples (i.g., in\nlazy_tid_reaped()).\n'intset' uses the integer set (src/backend/lib/integerset.c) to record\ndead tuples TIDs. It's an in-memory data structure to hold 64-bit\nintegers.\n\nIn the experiments, I created the table with 4GB and made 20% of total\ntuples dirty in all test cases while changing the distribution of\nwhere dead tuples exist within the table. The table has only one\nindex, therefore I did't use parallel vacuum. I set enough\nmaintenance_work_mem so that the index scan runs only once. Here is\nthe result, showing the \"total execution time in second (heap scan\ntime/index vacuum time/table vacuum time/memory usage in MB)”. The\nnumbers are round down to the nearest decimal.\n\n1. Updated evenly the table (every block has at least one dead tuple).\narray : 22 (8/12/2/114)\narray-minmax : 20 (8/11/2/114)\nintset : 17 (7/8/1/19)\n\n2. Updated the middle of the table.\narray : 25 (6/19/0/114)\narray-minmax : 17 (6/11/0/114)\nintset : 17 (6/11/0/7)\n\n3. Updated the tail of the table.\narray : 25 (6/19/0/114)\narray-minmax : 18 (6/11/0/114)\nintset : 18 (6/11/0/5)\n\n4. Updated both the beginning and the tail of the table.\narray : 25 (6/19/0/114)\narray-minmax : 23 (6/17/0/114)\nintset : 21 (6/14/0/6)\n\nThe memory usage is calculated by (# of dead tuples *\nsizeof(ItemPointerData)) in both ‘array’ and ‘array-minmax’ case,\nalthough the actual amount of palloc'd memory is different, and by\nintset_memory_usage() in ‘intset’ case.\n\nUsing the integer set is very memory efficient (5MB vs. 114MB in the\nbase case) and there is no 1GB limitation. Looking at the execution\ntime, I had expected that using the integer set is slower on recording\nTIDs than using the simple array but in this experiment, there is no\nbig difference among methods. Perhaps the result will vary if vacuum\nneeds to record much more dead tuple TIDs. From the results, I can see\na good improvement in the integer set case and probably a good start\nbut if we want to use it also for lazy vacuum, we will need to improve\nit so that it can be used on DSA for the parallel vacuum.\n\nI've attached the patch I used for the experiment that adds xx_vacuum\nGUC parameter that controls the method of recording TIDs. Please note\nthat it doesn't support parallel vacuum.\n\nRegards,\n\n\n--\nMasahiko Sawada http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Fri, 30 Oct 2020 10:43:56 +0900", "msg_from": "Masahiko Sawada <masahiko.sawada@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: Boundary value check in lazy_tid_reaped()" }, { "msg_contents": "On 2020-10-30 02:43, Masahiko Sawada wrote:\n> Using the integer set is very memory efficient (5MB vs. 114MB in the\n> base case) and there is no 1GB limitation. Looking at the execution\n> time, I had expected that using the integer set is slower on recording\n> TIDs than using the simple array but in this experiment, there is no\n> big difference among methods. Perhaps the result will vary if vacuum\n> needs to record much more dead tuple TIDs. From the results, I can see\n> a good improvement in the integer set case and probably a good start\n> but if we want to use it also for lazy vacuum, we will need to improve\n> it so that it can be used on DSA for the parallel vacuum.\n> \n> I've attached the patch I used for the experiment that adds xx_vacuum\n> GUC parameter that controls the method of recording TIDs. Please note\n> that it doesn't support parallel vacuum.\n\nHow do you want to proceed here? The approach of writing a wrapper for \nbsearch with bound check sounded like a good start. All the other ideas \ndiscussed here seem larger projects and would probably be out of scope \nof this commit fest.\n\n\n", "msg_date": "Wed, 20 Jan 2021 07:50:17 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Boundary value check in lazy_tid_reaped()" }, { "msg_contents": "On Wed, Jan 20, 2021 at 3:50 PM Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n>\n> On 2020-10-30 02:43, Masahiko Sawada wrote:\n> > Using the integer set is very memory efficient (5MB vs. 114MB in the\n> > base case) and there is no 1GB limitation. Looking at the execution\n> > time, I had expected that using the integer set is slower on recording\n> > TIDs than using the simple array but in this experiment, there is no\n> > big difference among methods. Perhaps the result will vary if vacuum\n> > needs to record much more dead tuple TIDs. From the results, I can see\n> > a good improvement in the integer set case and probably a good start\n> > but if we want to use it also for lazy vacuum, we will need to improve\n> > it so that it can be used on DSA for the parallel vacuum.\n> >\n> > I've attached the patch I used for the experiment that adds xx_vacuum\n> > GUC parameter that controls the method of recording TIDs. Please note\n> > that it doesn't support parallel vacuum.\n>\n> How do you want to proceed here? The approach of writing a wrapper for\n> bsearch with bound check sounded like a good start. All the other ideas\n> discussed here seem larger projects and would probably be out of scope\n> of this commit fest.\n\nAgreed. bsearch with bound check showed a reasonable improvement in my\nevaluation in terms of performance. Regarding memory efficiency, we\ncan experiment with other methods later.\n\nI've attached the patch that adds a bound check for encoded\nitermpointers before bsearch() in lazy_tid_reaped() and inlines the\nfunction.\n\nRegards,\n\n--\nMasahiko Sawada\nEDB: https://www.enterprisedb.com/", "msg_date": "Thu, 21 Jan 2021 22:11:52 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Boundary value check in lazy_tid_reaped()" }, { "msg_contents": "On 21.01.21 14:11, Masahiko Sawada wrote:\n> Agreed. bsearch with bound check showed a reasonable improvement in my\n> evaluation in terms of performance. Regarding memory efficiency, we\n> can experiment with other methods later.\n> \n> I've attached the patch that adds a bound check for encoded\n> itermpointers before bsearch() in lazy_tid_reaped() and inlines the\n> function.\n\nDo you have any data showing the effect of inlining lazy_tid_reaped()? \nI mean, it probably won't hurt, but it wasn't part of the original patch \nthat you tested, so I wonder whether it has any noticeable effect.\n\n\n", "msg_date": "Mon, 8 Mar 2021 11:16:16 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Boundary value check in lazy_tid_reaped()" }, { "msg_contents": "On Mon, Mar 8, 2021 at 7:16 PM Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n>\n> On 21.01.21 14:11, Masahiko Sawada wrote:\n> > Agreed. bsearch with bound check showed a reasonable improvement in my\n> > evaluation in terms of performance. Regarding memory efficiency, we\n> > can experiment with other methods later.\n> >\n> > I've attached the patch that adds a bound check for encoded\n> > itermpointers before bsearch() in lazy_tid_reaped() and inlines the\n> > function.\n>\n> Do you have any data showing the effect of inlining lazy_tid_reaped()?\n> I mean, it probably won't hurt, but it wasn't part of the original patch\n> that you tested, so I wonder whether it has any noticeable effect.\n\nI've done some benchmarks while changing the distribution of where\ndead tuples exist within the table. The table size is 4GB and 20% of\ntotal tuples are dirty. Here are the results of index vacuum execution\ntime:\n\n1. Updated evenly the table (every block has at least one dead tuple).\nmaster : 8.15\ninlining : 4.84\nnot-inlinning : 5.01\n\n2. Updated the middle of the table.\nmaster : 8.71\ninlining : 3.51\nnot-inlinning : 3.58\n\n3. Updated both the beginning and the tail of the table.\nmaster : 8.44\ninlining : 3.46\nnot-inlinning : 3.50\n\nThere is no noticeable effect of inlining lazy_tid_reaped(). So it\nwould be better to not do that.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Tue, 9 Mar 2021 09:57:31 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Boundary value check in lazy_tid_reaped()" }, { "msg_contents": "On Tue, Mar 9, 2021 at 9:57 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> On Mon, Mar 8, 2021 at 7:16 PM Peter Eisentraut\n> <peter.eisentraut@enterprisedb.com> wrote:\n> >\n> > On 21.01.21 14:11, Masahiko Sawada wrote:\n> > > Agreed. bsearch with bound check showed a reasonable improvement in my\n> > > evaluation in terms of performance. Regarding memory efficiency, we\n> > > can experiment with other methods later.\n> > >\n> > > I've attached the patch that adds a bound check for encoded\n> > > itermpointers before bsearch() in lazy_tid_reaped() and inlines the\n> > > function.\n> >\n> > Do you have any data showing the effect of inlining lazy_tid_reaped()?\n> > I mean, it probably won't hurt, but it wasn't part of the original patch\n> > that you tested, so I wonder whether it has any noticeable effect.\n>\n> I've done some benchmarks while changing the distribution of where\n> dead tuples exist within the table. The table size is 4GB and 20% of\n> total tuples are dirty. Here are the results of index vacuum execution\n> time:\n>\n> 1. Updated evenly the table (every block has at least one dead tuple).\n> master : 8.15\n> inlining : 4.84\n> not-inlinning : 5.01\n>\n> 2. Updated the middle of the table.\n> master : 8.71\n> inlining : 3.51\n> not-inlinning : 3.58\n>\n> 3. Updated both the beginning and the tail of the table.\n> master : 8.44\n> inlining : 3.46\n> not-inlinning : 3.50\n>\n> There is no noticeable effect of inlining lazy_tid_reaped(). So it\n> would be better to not do that.\n\nAttached the patch that doesn't inline lazy_tid_reaped().\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/", "msg_date": "Wed, 10 Mar 2021 10:29:33 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Boundary value check in lazy_tid_reaped()" }, { "msg_contents": "On 10.03.21 02:29, Masahiko Sawada wrote:\n>> There is no noticeable effect of inlining lazy_tid_reaped(). So it\n>> would be better to not do that.\n> \n> Attached the patch that doesn't inline lazy_tid_reaped().\n\ncommitted\n\n\n", "msg_date": "Wed, 10 Mar 2021 15:53:29 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Boundary value check in lazy_tid_reaped()" }, { "msg_contents": "On Wed, Mar 10, 2021 at 11:53 PM Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n>\n> On 10.03.21 02:29, Masahiko Sawada wrote:\n> >> There is no noticeable effect of inlining lazy_tid_reaped(). So it\n> >> would be better to not do that.\n> >\n> > Attached the patch that doesn't inline lazy_tid_reaped().\n>\n> committed\n\nThank you!\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Thu, 11 Mar 2021 10:01:21 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Boundary value check in lazy_tid_reaped()" }, { "msg_contents": "On Wed, Sep 9, 2020 at 7:33 AM Peter Geoghegan <pg@bowt.ie> wrote:\n> On Tue, Sep 8, 2020 at 1:23 AM Masahiko Sawada\n> <masahiko.sawada@2ndquadrant.com> wrote:\n> > > > I wonder if you would also see a speed-up with a bsearch() replacement\n> > > > that is inlineable, so it can inline the comparator (instead of\n> > > > calling it through a function pointer). I wonder if something more\n> > > > like (lblk << 32 | loff) - (rblk << 32 | roff) would go faster than\n> > > > the branchy comparator.\n> > >\n> > > Erm, off course that expression won't work... should be << 16, but\n> > > even then it would only work with a bsearch that uses int64_t\n> > > comparators, so I take that part back.\n> >\n> > Yeah, it seems to worth benchmarking the speed-up with an inlining.\n> > I'll do some performance tests with/without inlining on top of\n> > checking boundary values.\n>\n> It sounds like Thomas was talking about something like\n> itemptr_encode() + itemptr_decode(). In case you didn't know, we\n> actually do something like this for the TID tuplesort used for CREATE\n> INDEX CONCURRENTLY.\n\nBTW I got around to trying this idea out for a specialised\nbsearch_itemptr() using a wide comparator, over here:\n\nhttps://www.postgresql.org/message-id/CA%2BhUKGKztHEWm676csTFjYzortziWmOcf8HDss2Zr0muZ2xfEg%40mail.gmail.com\n\n\n", "msg_date": "Mon, 15 Mar 2021 12:22:00 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Boundary value check in lazy_tid_reaped()" }, { "msg_contents": "On Sun, Mar 14, 2021 at 4:22 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> BTW I got around to trying this idea out for a specialised\n> bsearch_itemptr() using a wide comparator, over here:\n\nCool!\n\nI have another thing that should be considered when we revisit this\narea in the future: maybe we should structure the binary search to\nlookup multiple TIDs at once -- probably all of the TIDs from a given\nleaf page, taken together.\n\nThere is now an nbtree function used for tuple deletion (all tuple\ndeletion, not just bottom-up deletion) that works like this:\n_bt_delitems_delete_check(). I suspect that it would make sense to\ngeneralize it to do the same thing for regular VACUUM. Perhaps this\nidea would have to be combined with other techniques to show a real\nbenefit. It would probably be necessary to sort the TIDs first (just\nlike index_delete_sort() does for the _bt_delitems_delete_check() code\ntoday), but that's probably no big deal.\n\nIt is typical to have 200 - 400 TIDs on an nbtree leaf page without\nusing deduplication. And with deduplication enabled you can have as\nmany as 1300 TIDs on a single 8KiB nbtree leaf page. It's easy to\nimagine something like GCC's __builtin_prefetch() (or maybe just more\npredictable access patterns in our \"batch binary search\") making\neverything much faster through batching. This will also naturally make\nbtvacuumpage() much less \"branchy\", since of course it will no longer\nneed to process the page one TID at a time -- that helps too.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Tue, 16 Mar 2021 14:08:27 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: Boundary value check in lazy_tid_reaped()" }, { "msg_contents": "We could also go parallel in another direction - I have been mulling about\nwriting a \"vectorized\" bsearch which would use AVX2, where you look up 64\n(or more likely 32, so tids also fit in 256bit vector) tids at a time.\n\nThe trickiest part is that the search can complete at different iteration\nfor each value.\n\nOf course it is possible that this has a very bad RAM access behaviour and\nis no win at all even if it otherways works.\n\n--\nHannu Krosing\n\nOn Tue, Mar 16, 2021 at 10:08 PM Peter Geoghegan <pg@bowt.ie> wrote:\n\n> On Sun, Mar 14, 2021 at 4:22 PM Thomas Munro <thomas.munro@gmail.com>\n> wrote:\n> > BTW I got around to trying this idea out for a specialised\n> > bsearch_itemptr() using a wide comparator, over here:\n>\n> Cool!\n>\n> I have another thing that should be considered when we revisit this\n> area in the future: maybe we should structure the binary search to\n> lookup multiple TIDs at once -- probably all of the TIDs from a given\n> leaf page, taken together.\n>\n> There is now an nbtree function used for tuple deletion (all tuple\n> deletion, not just bottom-up deletion) that works like this:\n> _bt_delitems_delete_check(). I suspect that it would make sense to\n> generalize it to do the same thing for regular VACUUM. Perhaps this\n> idea would have to be combined with other techniques to show a real\n> benefit. It would probably be necessary to sort the TIDs first (just\n> like index_delete_sort() does for the _bt_delitems_delete_check() code\n> today), but that's probably no big deal.\n>\n> It is typical to have 200 - 400 TIDs on an nbtree leaf page without\n> using deduplication. And with deduplication enabled you can have as\n> many as 1300 TIDs on a single 8KiB nbtree leaf page. It's easy to\n> imagine something like GCC's __builtin_prefetch() (or maybe just more\n> predictable access patterns in our \"batch binary search\") making\n> everything much faster through batching. This will also naturally make\n> btvacuumpage() much less \"branchy\", since of course it will no longer\n> need to process the page one TID at a time -- that helps too.\n>\n> --\n> Peter Geoghegan\n>\n>\n>\n\nWe could also go parallel in another direction - I have been mulling about writing a \"vectorized\" bsearch which would use AVX2, where you look up 64 (or more likely 32, so tids also fit in 256bit vector) tids at a time.The trickiest part is that the search can complete at different iteration for each value.Of course it is possible that this has a very bad RAM access behaviour and is no win at all even if it otherways works.--Hannu KrosingOn Tue, Mar 16, 2021 at 10:08 PM Peter Geoghegan <pg@bowt.ie> wrote:On Sun, Mar 14, 2021 at 4:22 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> BTW I got around to trying this idea out for a specialised\n> bsearch_itemptr() using a wide comparator, over here:\n\nCool!\n\nI have another thing that should be considered when we revisit this\narea in the future: maybe we should structure the binary search to\nlookup multiple TIDs at once -- probably all of the TIDs from a given\nleaf page, taken together.\n\nThere is now an nbtree function used for tuple deletion (all tuple\ndeletion, not just bottom-up deletion) that works like this:\n_bt_delitems_delete_check(). I suspect that it would make sense to\ngeneralize it to do the same thing for regular VACUUM. Perhaps this\nidea would have to be combined with other techniques to show a real\nbenefit. It would probably be necessary to sort the TIDs first (just\nlike index_delete_sort() does for the _bt_delitems_delete_check() code\ntoday), but that's probably no big deal.\n\nIt is typical to have 200 - 400 TIDs on an nbtree leaf page without\nusing deduplication. And with deduplication enabled you can have as\nmany as 1300 TIDs on a single 8KiB nbtree leaf page. It's easy to\nimagine something like GCC's __builtin_prefetch() (or maybe just more\npredictable access patterns in our \"batch binary search\") making\neverything much faster through batching. This will also naturally make\nbtvacuumpage() much less \"branchy\", since of course it will no longer\nneed to process the page one TID at a time -- that helps too.\n\n-- \nPeter Geoghegan", "msg_date": "Tue, 16 Mar 2021 22:59:42 +0100", "msg_from": "Hannu Krosing <hannuk@google.com>", "msg_from_op": false, "msg_subject": "Re: Boundary value check in lazy_tid_reaped()" } ]
[ { "msg_contents": "Thanks.\n\nRegards.", "msg_date": "Sun, 30 Aug 2020 14:03:32 +0100", "msg_from": "David CARLIER <devnexen@gmail.com>", "msg_from_op": true, "msg_subject": "[PATCH v1] explicit_bzero.c: using explicit_memset on NetBSD" }, { "msg_contents": "On Sun, Aug 30, 2020 at 02:03:32PM +0100, David CARLIER wrote:\n> Thanks.\n\nDuring the addition of explicit_bzero(), there was an agreement to use\nmemset_s(), as it is blessed by the standard:\nhttps://www.postgresql.org/message-id/20190717211931.GA906@alvherre.pgsql\n\nSo what would be the advantage of explicit_memset() knowing that\nNetBSD has memset_s()? This also means that your patch is a no-op for\nNetBSD as HAVE_MEMSET_S would be set.\n--\nMichael", "msg_date": "Mon, 31 Aug 2020 11:48:40 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [PATCH v1] explicit_bzero.c: using explicit_memset on NetBSD" } ]
[ { "msg_contents": "The stats target can be set since commit d06215d03, but wasn't shown by psql.\n ALTER STATISISTICS .. SET STATISTICS n.\n\nNormal (1-D) stats targets are shown in \\d+ table.\nStats objects are shown in \\d (no plus).\nArguably, this should be shown only in \"verbose\" mode (\\d+).", "msg_date": "Mon, 31 Aug 2020 00:00:47 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": true, "msg_subject": "v13: show extended stats target in \\d" }, { "msg_contents": "\n\n\n\n\n‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn Monday, 31 August 2020 08:00, Justin Pryzby <pryzby@telsasoft.com> wrote:\n\n> The stats target can be set since commit d06215d03, but wasn't shown by psql.\n> ALTER STATISISTICS .. SET STATISTICS n.\n>\n> Normal (1-D) stats targets are shown in \\d+ table.\n> Stats objects are shown in \\d (no plus).\n> Arguably, this should be shown only in \"verbose\" mode (\\d+).\n\nThis seems rather useful. May I suggest you add it to the commitfest?\n\n//Georgios\n\n\n\n\n", "msg_date": "Mon, 31 Aug 2020 07:47:35 +0000", "msg_from": "gkokolatos@pm.me", "msg_from_op": false, "msg_subject": "Re: v13: show extended stats target in \\d" }, { "msg_contents": "On Mon, Aug 31, 2020 at 07:47:35AM +0000, gkokolatos@pm.me wrote:\n> ‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\n> On Monday, 31 August 2020 08:00, Justin Pryzby <pryzby@telsasoft.com> wrote:\n> \n> > The stats target can be set since commit d06215d03, but wasn't shown by psql.\n> > ALTER STATISISTICS .. SET STATISTICS n.\n> >\n> > Normal (1-D) stats targets are shown in \\d+ table.\n> > Stats objects are shown in \\d (no plus).\n> > Arguably, this should be shown only in \"verbose\" mode (\\d+).\n> \n> This seems rather useful. May I suggest you add it to the commitfest?\n\nI added at\nhttps://commitfest.postgresql.org/29/2712/\n\n+ appendPQExpBuffer(&buf, \" STATISTICS %s\",\n\nMaybe it should have a comma, like \", STATISTICS %s\"?\nSimilar to these:\n\n appendPQExpBuffer(&buf, \", ON TABLE %s\",\n|Triggers:\n| trg1 AFTER INSERT ON trigpart3 FOR EACH ROW EXECUTE FUNCTION trigger_nothing(), ON TABLE trigpart\n\nand:\n\tappendPQExpBufferStr(&buf, \", PARTITIONED\");\n|part_ee_ff FOR VALUES IN ('ee', 'ff'), PARTITIONED,\n\nAlso, now I wonder if CREATE STATISTICS should support some syntax to set the\ninitial target. Like:\n\n|CREATE STATISTICS abstats ON a,b FROM child.abc_202006 WITH(STATISTICS 111);\n\n-- \nJustin\n\n\n", "msg_date": "Mon, 31 Aug 2020 20:14:29 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": true, "msg_subject": "Re: v13: show extended stats target in \\d" }, { "msg_contents": "Hi Justin,\n\nOn 2020/08/31 14:00, Justin Pryzby wrote:\n> The stats target can be set since commit d06215d03, but wasn't shown by psql.\n> ALTER STATISISTICS .. SET STATISTICS n.\n> \n> Normal (1-D) stats targets are shown in \\d+ table.\n> Stats objects are shown in \\d (no plus).\n> Arguably, this should be shown only in \"verbose\" mode (\\d+).\n\nI tested your patch on 13beta3 and head (ab3c6d41).\nIt looks good to me. :-D\n\nThanks,\nTatsuro Yamada\n\n\n\n", "msg_date": "Tue, 01 Sep 2020 10:37:49 +0900", "msg_from": "Tatsuro Yamada <tatsuro.yamada.tf@nttcom.co.jp>", "msg_from_op": false, "msg_subject": "Re: v13: show extended stats target in \\d" }, { "msg_contents": "The following review has been posted through the commitfest application:\nmake installcheck-world: not tested\nImplements feature: not tested\nSpec compliant: not tested\nDocumentation: not tested\n\nHi,\r\n\r\nI will humbly disagree with the current review. I shall refrain from changing the status though because I do not have very strong feeling about it.\r\n\r\nI am in agreement that it is a helpful feature and as implemented, the result seems to be the desired one.\r\n\r\nHowever the patch contains:\r\n\r\n- \" 'm' = any(stxkind) AS mcv_enabled\\n\"\r\n+ \" 'm' = any(stxkind) AS mcv_enabled,\\n\"\r\n+ \" %s\"\r\n \"FROM pg_catalog.pg_statistic_ext stat \"\r\n \"WHERE stxrelid = '%s'\\n\"\r\n \"ORDER BY 1;\",\r\n+ (pset.sversion >= 130000 ? \"stxstattarget\\n\" : \"-1\\n\"),\r\n oid);\r\n\r\nThis seems to be breaking a bit the pattern in describeOneTableDetails().\r\nFirst, it is customary to write the whole query for the version in its own block. I do find this pattern rather helpful and clean. So in my humble opinion, the ternary expression should be replaced with a distinct if block that would implement stxstattarget. Second, setting the value to -1 as an indication of absence breaks the pattern a bit further. More on that bellow.\r\n\r\n+ if (strcmp(PQgetvalue(result, i, 8), \"-1\") != 0)\r\n+ appendPQExpBuffer(&buf, \" STATISTICS %s\",\r\n+ PQgetvalue(result, i, 8));\r\n+\r\n\r\nIn the same function, one will find a bit of a different pattern for printing the statistics, e.g.\r\n if (strcmp(PQgetvalue(result, i, 7), \"t\") == 0) \r\nI will again hold the opinion that if the query gets crafted a bit differently, one can inspect if the table has `stxstattarget` and then, go ahead and print the value.\r\n\r\nSomething in the lines of:\r\n if (strcmp(PQgetvalue(result, i, 8), \"t\") == 0)\r\n appendPQExpBuffer(&buf, \" STATISTICS %s\", PQgetvalue(result, i, 9));\r\n\r\nFinally, the patch might be more complete if a note is added in the documentation.\r\nHave you considered adding something in doc/src/sgml/ref/psql-ref.sgml? If no, will you consider it? If yes, why did you discard it?\r\n\r\nRegards,\r\nGeorgios", "msg_date": "Tue, 01 Sep 2020 12:35:19 +0000", "msg_from": "Georgios Kokolatos <gkokolatos@protonmail.com>", "msg_from_op": false, "msg_subject": "Re: v13: show extended stats target in \\d" }, { "msg_contents": "+1 on fixing this, since the ability to change stats target is new in\npg13.\n\nOn 2020-Aug-31, Justin Pryzby wrote:\n\n> Maybe it should have a comma, like \", STATISTICS %s\"?\n\nIt does need some separator. Maybe a comma is sufficient, but I'm not\nsure: that will fail when we add cross-relation stats, because the\nFROM clause will have more relations and possibly have commas too.\n\n Table \"public.ab1\"\n Column | Type | Collation | Nullable | Default | Storage | Stats target | Description\n--------+---------+-----------+----------+---------+---------+--------------+-------------\n a | integer | | | | plain | |\n b | integer | | | | plain | |\nStatistics objects:\n \"public\".\"ab1_a_b_stats\" (ndistinct, dependencies, mcv) ON a, b FROM ab1\n\n\n> Also, now I wonder if CREATE STATISTICS should support some syntax to set the\n> initial target. Like:\n> \n> |CREATE STATISTICS abstats ON a,b FROM child.abc_202006 WITH(STATISTICS 111);\n\nUmm, if true (on which I'm not sold), maybe it should appear in the\nparenthesized list that currently is just the stats type list:\n\n |CREATE STATISTICS abstats (STATISTICS 111) ON a,b FROM child.abc_202006;\n\nI'm not really convinced we need this.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 1 Sep 2020 17:08:25 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: v13: show extended stats target in \\d" }, { "msg_contents": "On Tue, Sep 01, 2020 at 05:08:25PM -0400, Alvaro Herrera wrote:\n>+1 on fixing this, since the ability to change stats target is new in\n>pg13.\n>\n>On 2020-Aug-31, Justin Pryzby wrote:\n>\n>> Maybe it should have a comma, like \", STATISTICS %s\"?\n>\n>It does need some separator. Maybe a comma is sufficient, but I'm not\n>sure: that will fail when we add cross-relation stats, because the\n>FROM clause will have more relations and possibly have commas too.\n>\n> Table \"public.ab1\"\n> Column | Type | Collation | Nullable | Default | Storage | Stats target | Description\n>--------+---------+-----------+----------+---------+---------+--------------+-------------\n> a | integer | | | | plain | |\n> b | integer | | | | plain | |\n>Statistics objects:\n> \"public\".\"ab1_a_b_stats\" (ndistinct, dependencies, mcv) ON a, b FROM ab1\n>\n>\n>> Also, now I wonder if CREATE STATISTICS should support some syntax to set the\n>> initial target. Like:\n>>\n>> |CREATE STATISTICS abstats ON a,b FROM child.abc_202006 WITH(STATISTICS 111);\n>\n>Umm, if true (on which I'm not sold), maybe it should appear in the\n>parenthesized list that currently is just the stats type list:\n>\n> |CREATE STATISTICS abstats (STATISTICS 111) ON a,b FROM child.abc_202006;\n>\n>I'm not really convinced we need this.\n>\n\nMe neither. IMHO it's somewhat similar to per-column statistics target,\nwhere we don't allow specifying that in CREATE TABLE and you have to do\n\n ALTER TABLE ... ALTER COLUMN ... SET STATISTICS n;\n\nas a separate step.\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, 1 Sep 2020 23:22:42 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: v13: show extended stats target in \\d" }, { "msg_contents": "On Tue, Sep 01, 2020 at 05:08:25PM -0400, Alvaro Herrera wrote:\n> +1 on fixing this, since the ability to change stats target is new in\n> pg13.\n> \n> On 2020-Aug-31, Justin Pryzby wrote:\n> \n> > Maybe it should have a comma, like \", STATISTICS %s\"?\n> \n> It does need some separator. Maybe a comma is sufficient, but I'm not\n> sure: that will fail when we add cross-relation stats, because the\n> FROM clause will have more relations and possibly have commas too.\n\nGood thought.\n\nYou said it'll \"fail\", but I guess you mean it could be confusing to look at.\n\nI didn't actually know that \"multiple tables\" were planned for MV stats.\nAnother consideration is expression stats (as compared with expression\nindexes). I don't see how that helps guide this decision at all, though.\n\nI think trying to parse \\d output is discouraged and a bad idea, but it's\nobviously not ok if the output is ambiguous.\n\nBut it's not ambiguous, since STATISTICS is capitalized and unquoted.\nArguably, \"nn\" could be construed as looking like a table alias, which doesn't\nmake sense here, and integer aliases would also need to be quoted (and seem\nunlikely and not useful).\n\n... FROM t1, t2, STATISTICS nn\n\nI think this is 1) unambiguous; 2) clear; 3) consistent with other output and\nwith the \"ALTER STATISTICS SET STATISTICS NN\" command. It could say \"SET\" but\nI don't think it's useful to include; 4) seems to reasonably anticipate future\nsupport for expressions and multiple tables; \n\nI'm happy if someone suggests something better, but I don't know what that\nwould be. Unless we hurried up and finished this for v13, and included\nstxstattarget.\nhttps://commitfest.postgresql.org/29/2692/\nhttps://www.postgresql.org/message-id/flat/c0939aba-3b12-b596-dd08-913dda4b40f0%40nttcom.co.jp_1#32680b2fe0ab473c58a33eb0f9f00d42\n\nMaybe it's not relevant, but I found these don't have a separator.\nppendPQExpBufferStr(&buf, \" DEFERRABLE\");\nppendPQExpBufferStr(&buf, \" INITIALLY DEFERRED\");\nppendPQExpBufferStr(&buf, \" INVALID\");\nppendPQExpBufferStr(&buf, \" PRIMARY KEY,\");\nppendPQExpBufferStr(&buf, \" REPLICA IDENTITY\");\nppendPQExpBufferStr(&buf, \" UNIQUE,\");\nppendPQExpBufferStr(&buf, \" UNIQUE CONSTRAINT,\");\nppendPQExpBufferStr(&buf, \" CLUSTER\");\nppendPQExpBufferStr(&buf, \" AS RESTRICTIVE\");\nppendPQExpBuffer(&buf, \"\\n TO %s\",\n\nThese look like the only similar things with more than a single separator:\nppendPQExpBuffer(&buf, \"\\n USING (%s)\",\nppendPQExpBuffer(&buf, \"\\n WITH CHECK (%s)\",\n\n-- \nJustin\n\n\n", "msg_date": "Sat, 5 Sep 2020 16:06:58 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": true, "msg_subject": "Re: v13: show extended stats target in \\d" }, { "msg_contents": "On Tue, Sep 1, 2020 at 2:08 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n> It does need some separator. Maybe a comma is sufficient, but I'm not\n> sure: that will fail when we add cross-relation stats, because the\n> FROM clause will have more relations and possibly have commas too.\n\nHow about a line break? That seems like a simple solution that takes\nall the competing concerns into account.\n\nThe fact that that will stand out isn't necessarily a bad thing. I\nthink it's a good thing.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Sun, 6 Sep 2020 13:06:05 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: v13: show extended stats target in \\d" }, { "msg_contents": "On Sun, Sep 06, 2020 at 01:06:05PM -0700, Peter Geoghegan wrote:\n> On Tue, Sep 1, 2020 at 2:08 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n> > It does need some separator. Maybe a comma is sufficient, but I'm not\n> > sure: that will fail when we add cross-relation stats, because the\n> > FROM clause will have more relations and possibly have commas too.\n> \n> How about a line break? That seems like a simple solution that takes\n> all the competing concerns into account.\n> \n> The fact that that will stand out isn't necessarily a bad thing. I\n> think it's a good thing.\n\nLike this ?\n\npostgres=# \\d t \n Table \"public.t\"\n Column | Type | Collation | Nullable | Default\n--------+---------+-----------+----------+---------\n a | integer | | |\n b | integer | | |\nStatistics objects:\n \"public\".\"t\" (ndistinct, dependencies, mcv) ON a, b FROM t\n\nAre there any other examples of similarly related information spread across\nlines ?\n\nI find that to be too verbose ; I guess it could be shown only in \\d+, which is\ntrue of column stats.\n\nIt's weird that the quoting rules are different for the stats object vs the\ncolumns and the table. The schema qualification is also divergent. Also,\n\"public.t\" form is technically wrong (the objects should be *separately*\nquoted), but seems to be used all over. If the table or schema has a dot, it's\nambiguous what this means: Table \"public.public.t\".\n\n-- \nJustin\n\n\n", "msg_date": "Sun, 6 Sep 2020 15:48:23 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": true, "msg_subject": "Re: v13: show extended stats target in \\d" }, { "msg_contents": "On Sun, Sep 6, 2020 at 1:48 PM Justin Pryzby <pryzby@telsasoft.com> wrote:\n> On Sun, Sep 06, 2020 at 01:06:05PM -0700, Peter Geoghegan wrote:\n> > How about a line break? That seems like a simple solution that takes\n> > all the competing concerns into account.\n\n> Like this ?\n\n> Statistics objects:\n> \"public\".\"t\" (ndistinct, dependencies, mcv) ON a, b FROM t\n\nNo, not like that.\n\nISTM that the problem with your original proposal is that it suggests\nthat it ought to be possible to add \"STATISTICS 0\" to the end of a\nCREATE STATISTICS statement. That's not accurate, though. In reality\nthe only way to set the statistics target for a statistics object is\nwith ALTER STATISTICS. We should attempt to convey that difference\nhere.\n\nMore concretely, I was suggesting including a second line that's\nsimilar to the following example output (iff the statistics target has\nactually been set):\n\nStatistics objects:\n \"public\".\"t\" (ndistinct, dependencies, mcv) ON a, b FROM t\n (STATISTICS 0)\n\nMaybe some variation would be better -- the precise details are not\nimportant. The new line conveys the fact that STATISTICS 0 is a part\nof the object, but cannot appear in CREATE STATISTICS itself. That\nseems like the right way of framing this.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Mon, 7 Sep 2020 14:31:07 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: v13: show extended stats target in \\d" }, { "msg_contents": "On Tue, Sep 01, 2020 at 12:35:19PM +0000, Georgios Kokolatos wrote:\n> I will humbly disagree with the current review. I shall refrain from changing the status though because I do not have very strong feeling about it.\n\nSorry but this was in my spam, and didn't see until now.\n\n> \n> However the patch contains:\n> \n> - \" 'm' = any(stxkind) AS mcv_enabled\\n\"\n> + \" 'm' = any(stxkind) AS mcv_enabled,\\n\"\n> + \" %s\"\n> \"FROM pg_catalog.pg_statistic_ext stat \"\n> \"WHERE stxrelid = '%s'\\n\"\n> \"ORDER BY 1;\",\n> + (pset.sversion >= 130000 ? \"stxstattarget\\n\" : \"-1\\n\"),\n> oid);\n> \n> This seems to be breaking a bit the pattern in describeOneTableDetails().\n> First, it is customary to write the whole query for the version in its own block. I do find this pattern rather helpful and clean. So in my humble opinion, the ternary expression should be replaced with a distinct if block that would implement stxstattarget. Second, setting the value to -1 as an indication of absence breaks the pattern a bit further. More on that bellow.\n\nHm, I did like this using the \"hastriggers\" code as a template. But you're\nright that everywhere else does it differently.\n\n> + if (strcmp(PQgetvalue(result, i, 8), \"-1\") != 0)\n> + appendPQExpBuffer(&buf, \" STATISTICS %s\",\n> + PQgetvalue(result, i, 8));\n> +\n> \n> In the same function, one will find a bit of a different pattern for printing the statistics, e.g.\n> if (strcmp(PQgetvalue(result, i, 7), \"t\") == 0) \n> I will again hold the opinion that if the query gets crafted a bit differently, one can inspect if the table has `stxstattarget` and then, go ahead and print the value.\n> \n> Something in the lines of:\n> if (strcmp(PQgetvalue(result, i, 8), \"t\") == 0)\n> appendPQExpBuffer(&buf, \" STATISTICS %s\", PQgetvalue(result, i, 9));\n\nI think what you've written wouldn't give the desired behavior, since it would\nshow the stats target even when it's set to the default. I don't see the point\nof having additional, separate, version-specific boolean columns for 1) column\nexists; 2) column is not default, in addition to 3) column value. But I added\ncomment about what Peter and I agree is desirable, anyway.\n\n> Finally, the patch might be more complete if a note is added in the documentation.\n> Have you considered adding something in doc/src/sgml/ref/psql-ref.sgml? If no, will you consider it? If yes, why did you discard it?\n\nI don't think the details of psql output are currently documented. This shows\nnothing about column statistics target, nor about MV stats at all.\nhttps://www.postgresql.org/docs/13/app-psql.html\n\nAs for the discussion about a separator, I think maybe a comma is enough. I\ndoubt anyone is going to think that you can get a valid command by prefixing\nthis by \"CREATE STATISTICS\". Actually, it didn't even occur to me it was valid\ncommand without the stats target - after all, that's not true of indexes.\n\n+ \"public\".\"ab1_a_b_stats\" (ndistinct, dependencies, mcv) ON a, b FROM ab1, STATISTICS 0\n\nThis revision only shows the stats target in verbose mode (slash dee plus).\n\n-- \nJustin", "msg_date": "Wed, 9 Sep 2020 16:36:27 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": true, "msg_subject": "Re: v13: show extended stats target in \\d" }, { "msg_contents": "On 2020-Sep-09, Justin Pryzby wrote:\n\n> As for the discussion about a separator, I think maybe a comma is enough. I\n> doubt anyone is going to think that you can get a valid command by prefixing\n> this by \"CREATE STATISTICS\". Actually, it didn't even occur to me it was valid\n> command without the stats target - after all, that's not true of indexes.\n> \n> + \"public\".\"ab1_a_b_stats\" (ndistinct, dependencies, mcv) ON a, b FROM ab1, STATISTICS 0\n\nI vote to use a semicolon instead of comma, and otherwise +1.\n\n> This revision only shows the stats target in verbose mode (slash dee plus).\n\nI don't think this interferes enough with other stuff to relegate it to\nthe \"plus\" version, since it's not shown if default.\n\nTomas -- this needs to go in pg13, right?\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 9 Sep 2020 19:16:35 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: v13: show extended stats target in \\d" }, { "msg_contents": "On 2020-Sep-09, Justin Pryzby wrote:\n\n> As for the discussion about a separator, I think maybe a comma is enough. I\n> doubt anyone is going to think that you can get a valid command by prefixing\n> this by \"CREATE STATISTICS\". Actually, it didn't even occur to me it was valid\n> command without the stats target - after all, that's not true of indexes.\n\nBy the way, I got into this because of your comment in\nhttps://postgr.es/m/20200901011429.GZ5450@telsasoft.com on whether we\nneeded CREATE STATISTICS to have a clause for this.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 9 Sep 2020 19:22:30 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: v13: show extended stats target in \\d" }, { "msg_contents": "On Wed, Sep 09, 2020 at 07:22:30PM -0300, Alvaro Herrera wrote:\n> On 2020-Sep-09, Justin Pryzby wrote:\n> \n> > As for the discussion about a separator, I think maybe a comma is enough. I\n> > doubt anyone is going to think that you can get a valid command by prefixing\n> > this by \"CREATE STATISTICS\". Actually, it didn't even occur to me it was valid\n> > command without the stats target - after all, that's not true of indexes.\n> \n> By the way, I got into this because of your comment in\n> https://postgr.es/m/20200901011429.GZ5450@telsasoft.com on whether we\n> needed CREATE STATISTICS to have a clause for this.\n\nAnd I agree that it does not - the question was raised during development of\nthe feature, and nobody sees a need. I asked since I didn't know and I didn't\nwant it to be missed for lack of asking.\n\n-- \nJustin\n\n\n", "msg_date": "Wed, 9 Sep 2020 18:07:00 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": true, "msg_subject": "Re: v13: show extended stats target in \\d" }, { "msg_contents": "\n\n‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn Thursday, 10 September 2020 00:36, Justin Pryzby <pryzby@telsasoft.com> wrote:\n\n> On Tue, Sep 01, 2020 at 12:35:19PM +0000, Georgios Kokolatos wrote:\n>\n> > I will humbly disagree with the current review. I shall refrain from changing the status though because I do not have very strong feeling about it.\n>\n> Sorry but this was in my spam, and didn't see until now.\n\nNo worries at all. Thank you for replying.\n\n>\n> > However the patch contains:\n> >\n> > - \" 'm' = any(stxkind) AS mcv_enabled\\\\n\"\n> >\n> >\n> >\n> > - \" 'm' = any(stxkind) AS mcv_enabled,\\\\n\"\n> >\n> >\n> > - \" %s\"\n> > \"FROM pg_catalog.pg_statistic_ext stat \"\n> > \"WHERE stxrelid = '%s'\\\\n\"\n> > \"ORDER BY 1;\",\n> >\n> >\n> > - (pset.sversion >= 130000 ? \"stxstattarget\\\\n\" : \"-1\\\\n\"),\n> > oid);\n> >\n> >\n> >\n> > This seems to be breaking a bit the pattern in describeOneTableDetails().\n> > First, it is customary to write the whole query for the version in its own block. I do find this pattern rather helpful and clean. So in my humble opinion, the ternary expression should be replaced with a distinct if block that would implement stxstattarget. Second, setting the value to -1 as an indication of absence breaks the pattern a bit further. More on that bellow.\n>\n> Hm, I did like this using the \"hastriggers\" code as a template. But you're\n> right that everywhere else does it differently.\n\n\nThank you for taking my input.\n\n>\n> > - if (strcmp(PQgetvalue(result, i, 8), \"-1\") != 0)\n> >\n> >\n> > - appendPQExpBuffer(&buf, \" STATISTICS %s\",\n> >\n> >\n> > - PQgetvalue(result, i, 8));\n> >\n> >\n> > -\n> >\n> > In the same function, one will find a bit of a different pattern for printing the statistics, e.g.\n> > if (strcmp(PQgetvalue(result, i, 7), \"t\") == 0)\n> > I will again hold the opinion that if the query gets crafted a bit differently, one can inspect if the table has `stxstattarget` and then, go ahead and print the value.\n> > Something in the lines of:\n> > if (strcmp(PQgetvalue(result, i, 8), \"t\") == 0)\n> > appendPQExpBuffer(&buf, \" STATISTICS %s\", PQgetvalue(result, i, 9));\n>\n> I think what you've written wouldn't give the desired behavior, since it would\n> show the stats target even when it's set to the default. I don't see the point\n> of having additional, separate, version-specific boolean columns for 1) column\n> exists; 2) column is not default, in addition to 3) column value. But I added\n> comment about what Peter and I agree is desirable, anyway.\n\nFair enough. As I said above, I do not have a very strong feeling, so it gets my +1 if it is worth anything.\n\n\n>\n> > Finally, the patch might be more complete if a note is added in the documentation.\n> > Have you considered adding something in doc/src/sgml/ref/psql-ref.sgml? If no, will you consider it? If yes, why did you discard it?\n>\n> I don't think the details of psql output are currently documented. This shows\n> nothing about column statistics target, nor about MV stats at all.\n> https://www.postgresql.org/docs/13/app-psql.html\n\nYeah, I have noticed that. Hence my question. If anything maybe the documentation can be expanded to cover these cases in a different patch. Thank you for your answer.\n\n>\n> As for the discussion about a separator, I think maybe a comma is enough. I\n> doubt anyone is going to think that you can get a valid command by prefixing\n> this by \"CREATE STATISTICS\". Actually, it didn't even occur to me it was valid\n> command without the stats target - after all, that's not true of indexes.\n>\n> - \"public\".\"ab1_a_b_stats\" (ndistinct, dependencies, mcv) ON a, b FROM ab1, STATISTICS 0\n>\n> This revision only shows the stats target in verbose mode (slash dee plus).\n>\n> --\n> Justin\n>\n\n\n\n\n", "msg_date": "Thu, 10 Sep 2020 07:32:27 +0000", "msg_from": "Georgios <gkokolatos@protonmail.com>", "msg_from_op": false, "msg_subject": "Re: v13: show extended stats target in \\d" }, { "msg_contents": "On 2020-Sep-09, Justin Pryzby wrote:\n\n> As for the discussion about a separator, I think maybe a comma is enough. I\n> doubt anyone is going to think that you can get a valid command by prefixing\n> this by \"CREATE STATISTICS\". Actually, it didn't even occur to me it was valid\n> command without the stats target - after all, that's not true of indexes.\n> \n> + \"public\".\"ab1_a_b_stats\" (ndistinct, dependencies, mcv) ON a, b FROM ab1, STATISTICS 0\n> \n> This revision only shows the stats target in verbose mode (slash dee plus).\n\nI put it back to show in non-verbose mode; after all it's only in the\ninfrequent case that it's set to anything at all, and also it doesn't\ntake up another column, as is the case with per-column stats targets.\n\nI changed the separator from comma to semicolon, because it seems a\nlittle less ambiguous. It's easy to change if people hate that.\n\n... and pushed. Thanks.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 11 Sep 2020 16:26:47 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: v13: show extended stats target in \\d" } ]
[ { "msg_contents": "Hi all,\n\nWe are going to be in September in a couple of hours, meaning that the\nsecond commit fest for Postgres 14 will begin soon. Do we have any\nvolunteers to take the role of CFM this time?\n\nThanks,\n--\nMichael", "msg_date": "Mon, 31 Aug 2020 16:37:12 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Manager for commit fest 2020-09" }, { "msg_contents": "On Mon, Aug 31, 2020 at 04:37:12PM +0900, Michael Paquier wrote:\n> We are going to be in September in a couple of hours, meaning that the\n> second commit fest for Postgres 14 will begin soon. Do we have any\n> volunteers to take the role of CFM this time?\n\nAs of the moment this message is written, 10 hours remain until we are\nthe 1st of September AoE, where I'll switch the commit fest as\nofficially in progress. It will not be possible to register new\npatches to 2020-09 after that.\n--\nMichael", "msg_date": "Tue, 1 Sep 2020 10:43:47 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Manager for commit fest 2020-09" }, { "msg_contents": "On Tue, Sep 01, 2020 at 10:43:47AM +0900, Michael Paquier wrote:\n> As of the moment this message is written, 10 hours remain until we are\n> the 1st of September AoE, where I'll switch the commit fest as\n> officially in progress. It will not be possible to register new\n> patches to 2020-09 after that.\n\nThe commit fest is marked as officially running now. Not seeing any\nvolunteers around, I'll do the CFM duties for this one.\n--\nMichael", "msg_date": "Wed, 2 Sep 2020 09:15:03 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Manager for commit fest 2020-09" }, { "msg_contents": "On 2020/09/01 10:43, Michael Paquier wrote:\n> On Mon, Aug 31, 2020 at 04:37:12PM +0900, Michael Paquier wrote:\n>> We are going to be in September in a couple of hours, meaning that the\n>> second commit fest for Postgres 14 will begin soon. Do we have any\n>> volunteers to take the role of CFM this time?\n> \n> As of the moment this message is written, 10 hours remain until we are\n> the 1st of September AoE, where I'll switch the commit fest as\n> officially in progress. It will not be possible to register new\n> patches to 2020-09 after that.\n\n2020-11 is also now showing as \"in progress\", is that correct?\n\n\nRegards\n\nIan Barwick\n\n\n-- \nIan Barwick https://www.2ndQuadrant.com/\n PostgreSQL Development, 24x7 Support, Training & Services\n\n\n", "msg_date": "Wed, 2 Sep 2020 09:28:07 +0900", "msg_from": "Ian Barwick <ian.barwick@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Manager for commit fest 2020-09" }, { "msg_contents": "On Wed, Sep 02, 2020 at 09:28:07AM +0900, Ian Barwick wrote:\n> 2020-11 is also now showing as \"in progress\", is that correct?\n\nIt was not. Thanks!\n--\nMichael", "msg_date": "Wed, 2 Sep 2020 09:30:45 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Manager for commit fest 2020-09" }, { "msg_contents": "On Tue, Sep 01, 2020 at 10:43:47AM +0900, Michael Paquier wrote:\n> As of the moment this message is written, 10 hours remain until we are\n> the 1st of September AoE, where I'll switch the commit fest as\n> officially in progress. It will not be possible to register new\n> patches to 2020-09 after that.\n\nAnd one month later, here we are with the following results and a CF\nnow closed:\nCommitted: 48\nMoved to next CF: 147\nWithdrawn: 4\nRejected: 3\nReturned with Feedback: 33\nTotal: 235\n\nI have noticed that a lot of patches, more than usual actually per the\nimpression I got, had an incorrect status. When sending a rebased\npatch or after doing a review, please make sure that the status of the\npatch is updated accordingly. This helps in making less mistakes when\npatches are moved around. A second thing is that we had, as usual, a\nhigh number of patches waiting in the app for more than one commit\nfest, waiting for some good souls to review them.\n--\nMichael", "msg_date": "Thu, 1 Oct 2020 13:51:57 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Manager for commit fest 2020-09" }, { "msg_contents": "Michael Paquier <michael@paquier.xyz> writes:\n> And one month later, here we are with the following results and a CF\n> now closed:\n> Committed: 48\n> Moved to next CF: 147\n> Withdrawn: 4\n> Rejected: 3\n> Returned with Feedback: 33\n> Total: 235\n\nOnce again, thanks for doing all that tedious work!\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 01 Oct 2020 10:04:25 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Manager for commit fest 2020-09" } ]
[ { "msg_contents": "Hi,\n\nAfter commit 3e98c0bafb28de, we can display the usage of the\nmemory contexts using pg_backend_memory_contexts system\nview.\n\nHowever, its target is limited to the process attached to\nthe current session.\n\nAs discussed in the thread[1], it'll be useful to make it\npossible to get the memory contexts of an arbitrary backend\nprocess.\n\nAttached PoC patch makes pg_get_backend_memory_contexts()\ndisplay meory contexts of the specified PID of the process.\n\n\n =# -- PID of the target process is 17051\n =# SELECT * FROM pg_get_backend_memory_contexts(17051) ;\n name | ident | parent | level | \ntotal_bytes | total_nblocks | free_bytes | free_chunks | used_bytes\n \n-----------------------+-------+------------------+-------+-------------+---------------+------------+-------------+------------\n TopMemoryContext | | | 0 | \n68720 | 5 | 16816 | 16 | 51904\n RowDescriptionContext | | TopMemoryContext | 1 | \n8192 | 1 | 6880 | 0 | 1312\n MessageContext | | TopMemoryContext | 1 | \n65536 | 4 | 19912 | 1 | 45624\n ...\n\nIt doesn't display contexts of all the backends but only\nthe contexts of specified process.\nI think it would be enough because I suppose this function\nis used after investigations using ps command or other OS\nlevel utilities.\n\n\nThe rough idea of implementation is like below:\n\n 1. send a signal to the specified process\n 2. signaled process dumps its memory contexts to a file\n 3. read the dumped file and display it to the user\n\n\nAny thoughts?\n\n[1] \nhttps://www.postgresql.org/message-id/72a656e0f71d0860161e0b3f67e4d771%40oss.nttdata.com\n\n\nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA CORPORATION", "msg_date": "Mon, 31 Aug 2020 20:22:18 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Get memory contexts of an arbitrary backend process" }, { "msg_contents": "Hi,\n\nOn Mon, Aug 31, 2020 at 8:22 PM torikoshia <torikoshia@oss.nttdata.com> wrote:\n> As discussed in the thread[1], it'll be useful to make it\n> possible to get the memory contexts of an arbitrary backend\n> process.\n+1\n\n> Attached PoC patch makes pg_get_backend_memory_contexts()\n> display meory contexts of the specified PID of the process.\nThanks, it's a very good patch for discussion.\n\n> It doesn't display contexts of all the backends but only\n> the contexts of specified process.\nor we can \"SELECT (pg_get_backend_memory_contexts(pid)).* FROM\npg_stat_activity WHERE ...\",\nso I don't think it's a big deal.\n\n> The rough idea of implementation is like below:\n>\n> 1. send a signal to the specified process\n> 2. signaled process dumps its memory contexts to a file\n> 3. read the dumped file and display it to the user\nI agree with the overview of the idea.\nHere are some comments and questions.\n\n- Currently, \"the signal transmission for dumping memory information\"\nand \"the read & output of dump information \"\n are on the same interface, but I think it would be better to separate them.\n How about providing the following three types of functions for users?\n - send a signal to specified pid\n - check the status of the signal sent and received\n - read the dumped information\n- How about managing the status of signal send/receive and dump\noperations on a shared hash or others ?\n Sending and receiving signals, dumping memory information, and\nreferencing dump information all work asynchronously.\n Therefore, it would be good to have management information to check\nthe status of each process.\n A simple idea is that ..\n - send a signal to dump to a PID, it first record following\ninformation into the shared hash.\n pid (specified pid)\n loc (dump location, currently might be ASAP)\n recv (did the pid process receive a signal? first false)\n dumped (did the pid process dump a mem information? first false)\n - specified process receive the signal, update the status in the\nshared hash, then dumped at specified location.\n - specified process finish dump mem information, update the status\nin the shared hash.\n- Does it allow one process to output multiple dump files?\n It appears to be a specification to overwrite at present, but I\nthought it would be good to be able to generate\n multiple dump files in different phases (e.g., planning phase and\nexecution phase) in the future.\n- How is the dump file cleaned up?\n\nBest regards,\n\n-- \nTatsuhito Kasahara\nkasahara.tatsuhito _at_ gmail.com\n\n\n", "msg_date": "Tue, 1 Sep 2020 00:03:08 +0900", "msg_from": "Kasahara Tatsuhito <kasahara.tatsuhito@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "Hi\n\npo 31. 8. 2020 v 17:03 odesílatel Kasahara Tatsuhito <\nkasahara.tatsuhito@gmail.com> napsal:\n\n> Hi,\n>\n> On Mon, Aug 31, 2020 at 8:22 PM torikoshia <torikoshia@oss.nttdata.com>\n> wrote:\n> > As discussed in the thread[1], it'll be useful to make it\n> > possible to get the memory contexts of an arbitrary backend\n> > process.\n> +1\n>\n> > Attached PoC patch makes pg_get_backend_memory_contexts()\n> > display meory contexts of the specified PID of the process.\n> Thanks, it's a very good patch for discussion.\n>\n> > It doesn't display contexts of all the backends but only\n> > the contexts of specified process.\n> or we can \"SELECT (pg_get_backend_memory_contexts(pid)).* FROM\n> pg_stat_activity WHERE ...\",\n> so I don't think it's a big deal.\n>\n> > The rough idea of implementation is like below:\n> >\n> > 1. send a signal to the specified process\n> > 2. signaled process dumps its memory contexts to a file\n> > 3. read the dumped file and display it to the user\n> I agree with the overview of the idea.\n> Here are some comments and questions.\n>\n> - Currently, \"the signal transmission for dumping memory information\"\n> and \"the read & output of dump information \"\n> are on the same interface, but I think it would be better to separate\n> them.\n> How about providing the following three types of functions for users?\n> - send a signal to specified pid\n> - check the status of the signal sent and received\n> - read the dumped information\n> - How about managing the status of signal send/receive and dump\n> operations on a shared hash or others ?\n> Sending and receiving signals, dumping memory information, and\n> referencing dump information all work asynchronously.\n> Therefore, it would be good to have management information to check\n> the status of each process.\n> A simple idea is that ..\n> - send a signal to dump to a PID, it first record following\n> information into the shared hash.\n> pid (specified pid)\n> loc (dump location, currently might be ASAP)\n> recv (did the pid process receive a signal? first false)\n> dumped (did the pid process dump a mem information? first false)\n> - specified process receive the signal, update the status in the\n> shared hash, then dumped at specified location.\n> - specified process finish dump mem information, update the status\n> in the shared hash.\n> - Does it allow one process to output multiple dump files?\n> It appears to be a specification to overwrite at present, but I\n> thought it would be good to be able to generate\n> multiple dump files in different phases (e.g., planning phase and\n> execution phase) in the future.\n> - How is the dump file cleaned up?\n>\n\n For a very long time there has been similar discussion about taking\nsession query and session execution plans from other sessions.\n\nI am not sure how necessary information is in the memory dump, but I am\nsure so taking the current execution plan and complete text of the current\nquery is pretty necessary information.\n\nbut can be great so this infrastructure can be used for any debugging\npurpose.\n\nRegards\n\nPavel\n\n\n> Best regards,\n>\n> --\n> Tatsuhito Kasahara\n> kasahara.tatsuhito _at_ gmail.com\n>\n>\n>\n\nHipo 31. 8. 2020 v 17:03 odesílatel Kasahara Tatsuhito <kasahara.tatsuhito@gmail.com> napsal:Hi,\n\nOn Mon, Aug 31, 2020 at 8:22 PM torikoshia <torikoshia@oss.nttdata.com> wrote:\n> As discussed in the thread[1], it'll be useful to make it\n> possible to get the memory contexts of an arbitrary backend\n> process.\n+1\n\n> Attached PoC patch makes pg_get_backend_memory_contexts()\n> display meory contexts of the specified PID of the process.\nThanks, it's a very good patch for discussion.\n\n> It doesn't display contexts of all the backends but only\n> the contexts of specified process.\nor we can  \"SELECT (pg_get_backend_memory_contexts(pid)).* FROM\npg_stat_activity WHERE ...\",\nso I don't think it's a big deal.\n\n> The rough idea of implementation is like below:\n>\n>    1. send  a signal to the specified process\n>    2. signaled process dumps its memory contexts to a file\n>    3. read the dumped file and display it to the user\nI agree with the overview of the idea.\nHere are some comments and questions.\n\n- Currently, \"the signal transmission for dumping memory information\"\nand \"the read & output of dump information \"\n  are on the same interface, but I think it would be better to separate them.\n  How about providing the following three types of functions for users?\n  - send a signal to specified pid\n  - check the status of the signal sent and received\n  - read the dumped information\n- How about managing the status of signal send/receive and dump\noperations on a shared hash or others ?\n  Sending and receiving signals, dumping memory information, and\nreferencing dump information all work asynchronously.\n  Therefore, it would be good to have management information to check\nthe status of each process.\n  A simple idea is that ..\n   - send a signal to dump to a PID, it first record following\ninformation into the shared hash.\n     pid (specified pid)\n     loc (dump location, currently might be ASAP)\n     recv (did the pid process receive a signal? first false)\n     dumped (did the pid process dump a mem information?  first false)\n   - specified process receive the signal, update the status in the\nshared hash, then dumped at specified location.\n   - specified process finish dump mem information,  update the status\nin the shared hash.\n- Does it allow one process to output multiple dump files?\n  It appears to be a specification to overwrite at present, but I\nthought it would be good to be able to generate\n  multiple dump files in different phases (e.g., planning phase and\nexecution phase) in the future.\n- How is the dump file cleaned up? For a very long time there has been similar discussion about taking session query and session execution plans from other sessions.I am not sure how necessary information is in the memory dump, but I am sure so taking the current execution plan and complete text of the current query is pretty necessary information. but can be great so this infrastructure can be used for any debugging purpose.RegardsPavel\n\nBest regards,\n\n-- \nTatsuhito Kasahara\nkasahara.tatsuhito _at_ gmail.com", "msg_date": "Mon, 31 Aug 2020 20:29:47 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "Hi,\n\nOn 2020-08-31 20:22:18 +0900, torikoshia wrote:\n> After commit 3e98c0bafb28de, we can display the usage of the\n> memory contexts using pg_backend_memory_contexts system\n> view.\n> \n> However, its target is limited to the process attached to\n> the current session.\n> \n> As discussed in the thread[1], it'll be useful to make it\n> possible to get the memory contexts of an arbitrary backend\n> process.\n> \n> Attached PoC patch makes pg_get_backend_memory_contexts()\n> display meory contexts of the specified PID of the process.\n\nAwesome!\n\n\n> It doesn't display contexts of all the backends but only\n> the contexts of specified process.\n> I think it would be enough because I suppose this function\n> is used after investigations using ps command or other OS\n> level utilities.\n\nIt can be used as a building block if all are needed. Getting the\ninfrastructure right is the big thing here, I think. Adding more\ndetailed views on top of that data later is easier.\n\n\n\n> diff --git a/src/backend/catalog/system_views.sql b/src/backend/catalog/system_views.sql\n> index a2d61302f9..88fb837ecd 100644\n> --- a/src/backend/catalog/system_views.sql\n> +++ b/src/backend/catalog/system_views.sql\n> @@ -555,10 +555,10 @@ REVOKE ALL ON pg_shmem_allocations FROM PUBLIC;\n> REVOKE EXECUTE ON FUNCTION pg_get_shmem_allocations() FROM PUBLIC;\n> \n> CREATE VIEW pg_backend_memory_contexts AS\n> - SELECT * FROM pg_get_backend_memory_contexts();\n> + SELECT * FROM pg_get_backend_memory_contexts(-1);\n\n-1 is odd. Why not use NULL or even 0?\n\n> +\telse\n> +\t{\n> +\t\tint\t\t\trc;\n> +\t\tint parent_len = strlen(parent);\n> +\t\tint name_len = strlen(name);\n> +\n> +\t\t/*\n> +\t\t * write out the current memory context information.\n> +\t\t * Since some elements of values are reusable, we write it out.\n\nNot sure what the second comment line here is supposed to mean?\n\n\n> +\t\t */\n> +\t\tfputc('D', fpout);\n> +\t\trc = fwrite(values, sizeof(values), 1, fpout);\n> +\t\trc = fwrite(nulls, sizeof(nulls), 1, fpout);\n> +\n> +\t\t/* write out information which is not resuable from serialized values */\n\ns/resuable/reusable/\n\n\n> +\t\trc = fwrite(&name_len, sizeof(int), 1, fpout);\n> +\t\trc = fwrite(name, name_len, 1, fpout);\n> +\t\trc = fwrite(&idlen, sizeof(int), 1, fpout);\n> +\t\trc = fwrite(clipped_ident, idlen, 1, fpout);\n> +\t\trc = fwrite(&level, sizeof(int), 1, fpout);\n> +\t\trc = fwrite(&parent_len, sizeof(int), 1, fpout);\n> +\t\trc = fwrite(parent, parent_len, 1, fpout);\n> +\t\t(void) rc;\t\t\t\t/* we'll check for error with ferror */\n> +\n> +\t}\n\nThis format is not descriptive. How about serializing to json or\nsomething? Or at least having field names?\n\nAlternatively, build the same tuple we build for the SRF, and serialize\nthat. Then there's basically no conversion needed.\n\n\n> @@ -117,6 +157,8 @@ PutMemoryContextsStatsTupleStore(Tuplestorestate *tupstore,\n> Datum\n> pg_get_backend_memory_contexts(PG_FUNCTION_ARGS)\n> {\n> +\tint\t\t\tpid = PG_GETARG_INT32(0);\n> +\n> \tReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;\n> \tTupleDesc\ttupdesc;\n> \tTuplestorestate *tupstore;\n> @@ -147,11 +189,258 @@ pg_get_backend_memory_contexts(PG_FUNCTION_ARGS)\n> \n> \tMemoryContextSwitchTo(oldcontext);\n> \n> -\tPutMemoryContextsStatsTupleStore(tupstore, tupdesc,\n> -\t\t\t\t\t\t\t\tTopMemoryContext, NULL, 0);\n> +\tif (pid == -1)\n> +\t{\n> +\t\t/*\n> +\t\t * Since pid -1 indicates target is the local process, simply\n> +\t\t * traverse memory contexts.\n> +\t\t */\n> +\t\tPutMemoryContextsStatsTupleStore(tupstore, tupdesc,\n> +\t\t\t\t\t\t\t\tTopMemoryContext, \"\", 0, NULL);\n> +\t}\n> +\telse\n> +\t{\n> +\t\t/*\n> +\t\t * Send signal for dumping memory contexts to the target process,\n> +\t\t * and read the dumped file.\n> +\t\t */\n> +\t\tFILE\t *fpin;\n> +\t\tchar\t\tdumpfile[MAXPGPATH];\n> +\n> +\t\tSendProcSignal(pid, PROCSIG_DUMP_MEMORY, InvalidBackendId);\n> +\n> +\t\tsnprintf(dumpfile, sizeof(dumpfile), \"pg_memusage/%d\", pid);\n> +\n> +\t\twhile (true)\n> +\t\t{\n> +\t\t\tCHECK_FOR_INTERRUPTS();\n> +\n> +\t\t\tpg_usleep(10000L);\n> +\n\nNeed better signalling back/forth here.\n\n\n\n> +/*\n> + * dump_memory_contexts\n> + * \tDumping local memory contexts to a file.\n> + * \tThis function does not delete the file as it is intended to be read by\n> + * \tanother process.\n> + */\n> +static void\n> +dump_memory_contexts(void)\n> +{\n> +\tFILE\t *fpout;\n> +\tchar\t\ttmpfile[MAXPGPATH];\n> +\tchar\t\tdumpfile[MAXPGPATH];\n> +\n> +\tsnprintf(tmpfile, sizeof(tmpfile), \"pg_memusage/%d.tmp\", MyProcPid);\n> +\tsnprintf(dumpfile, sizeof(dumpfile), \"pg_memusage/%d\", MyProcPid);\n> +\n> +\t/*\n> +\t * Open a temp file to dump the current memory context.\n> +\t */\n> +\tfpout = AllocateFile(tmpfile, PG_BINARY_W);\n> +\tif (fpout == NULL)\n> +\t{\n> +\t\tereport(LOG,\n> +\t\t\t\t(errcode_for_file_access(),\n> +\t\t\t\t errmsg(\"could not write temporary memory context file \\\"%s\\\": %m\",\n> +\t\t\t\t\t\ttmpfile)));\n> +\t\treturn;\n> +\t}\n\nProbably should be opened with O_CREAT | O_TRUNC?\n\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 31 Aug 2020 18:54:29 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On 2020-09-01 03:29, Pavel Stehule wrote:\n> Hi\n> \n> po 31. 8. 2020 v 17:03 odesílatel Kasahara Tatsuhito\n> <kasahara.tatsuhito@gmail.com> napsal:\n> \n>> Hi,\n>> \n>> On Mon, Aug 31, 2020 at 8:22 PM torikoshia\n>> <torikoshia@oss.nttdata.com> wrote:\n>>> As discussed in the thread[1], it'll be useful to make it\n>>> possible to get the memory contexts of an arbitrary backend\n>>> process.\n>> +1\n>> \n>>> Attached PoC patch makes pg_get_backend_memory_contexts()\n>>> display meory contexts of the specified PID of the process.\n>> Thanks, it's a very good patch for discussion.\n>> \n>>> It doesn't display contexts of all the backends but only\n>>> the contexts of specified process.\n>> or we can \"SELECT (pg_get_backend_memory_contexts(pid)).* FROM\n>> pg_stat_activity WHERE ...\",\n>> so I don't think it's a big deal.\n>> \n>>> The rough idea of implementation is like below:\n>>> \n>>> 1. send a signal to the specified process\n>>> 2. signaled process dumps its memory contexts to a file\n>>> 3. read the dumped file and display it to the user\n>> I agree with the overview of the idea.\n>> Here are some comments and questions.\n\nThanks for the comments!\n\n>> \n>> - Currently, \"the signal transmission for dumping memory\n>> information\"\n>> and \"the read & output of dump information \"\n>> are on the same interface, but I think it would be better to\n>> separate them.\n>> How about providing the following three types of functions for\n>> users?\n>> - send a signal to specified pid\n>> - check the status of the signal sent and received\n>> - read the dumped information\n\nIs this for future extensibility to make it possible to get\nother information like the current execution plan which was\nsuggested by Pavel?\n\nIf so, I agree with considering extensibility, but I'm not\nsure it's necessary whether providing these types of\nfunctions for 'users'.\n\n>> - How about managing the status of signal send/receive and dump\n>> operations on a shared hash or others ?\n>> Sending and receiving signals, dumping memory information, and\n>> referencing dump information all work asynchronously.\n>> Therefore, it would be good to have management information to\n>> check\n>> the status of each process.\n>> A simple idea is that ..\n>> - send a signal to dump to a PID, it first record following\n>> information into the shared hash.\n>> pid (specified pid)\n>> loc (dump location, currently might be ASAP)\n>> recv (did the pid process receive a signal? first false)\n>> dumped (did the pid process dump a mem information? first\n>> false)\n>> - specified process receive the signal, update the status in the\n>> shared hash, then dumped at specified location.\n>> - specified process finish dump mem information, update the\n>> status\n>> in the shared hash.\n\nAdding management information on shared memory seems necessary\nwhen we want to have more controls over dumping like 'dump\nlocation' or any other information such as 'current execution\nplan'.\nI'm going to consider this.\n\n\n>> - Does it allow one process to output multiple dump files?\n>> It appears to be a specification to overwrite at present, but I\n>> thought it would be good to be able to generate\n>> multiple dump files in different phases (e.g., planning phase and\n>> execution phase) in the future.\n>> - How is the dump file cleaned up?\n> \n> For a very long time there has been similar discussion about taking\n> session query and session execution plans from other sessions.\n> \n> I am not sure how necessary information is in the memory dump, but I\n> am sure so taking the current execution plan and complete text of the\n> current query is pretty necessary information.\n> \n> but can be great so this infrastructure can be used for any debugging\n> purpose.\n\nThanks!\nIt would be good if some part of this effort can be an infrastructure\nof other debugging.\nIt may be hard, but I will keep your comment in mind.\n\n\nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA CORPORATION\n\n> \n> Regards\n> \n> Pavel\n> \n>> Best regards,\n>> \n>> --\n>> Tatsuhito Kasahara\n>> kasahara.tatsuhito _at_ gmail.com [1]\n> \n> \n> Links:\n> ------\n> [1] http://gmail.com\n\n\n", "msg_date": "Thu, 03 Sep 2020 15:38:57 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "Thanks for reviewing!\n\nI'm going to modify the patch according to your comments.\n\nOn 2020-09-01 10:54, Andres Freund wrote:\n> Hi,\n> \n> On 2020-08-31 20:22:18 +0900, torikoshia wrote:\n>> After commit 3e98c0bafb28de, we can display the usage of the\n>> memory contexts using pg_backend_memory_contexts system\n>> view.\n>> \n>> However, its target is limited to the process attached to\n>> the current session.\n>> \n>> As discussed in the thread[1], it'll be useful to make it\n>> possible to get the memory contexts of an arbitrary backend\n>> process.\n>> \n>> Attached PoC patch makes pg_get_backend_memory_contexts()\n>> display meory contexts of the specified PID of the process.\n> \n> Awesome!\n> \n> \n>> It doesn't display contexts of all the backends but only\n>> the contexts of specified process.\n>> I think it would be enough because I suppose this function\n>> is used after investigations using ps command or other OS\n>> level utilities.\n> \n> It can be used as a building block if all are needed. Getting the\n> infrastructure right is the big thing here, I think. Adding more\n> detailed views on top of that data later is easier.\n> \n> \n> \n>> diff --git a/src/backend/catalog/system_views.sql \n>> b/src/backend/catalog/system_views.sql\n>> index a2d61302f9..88fb837ecd 100644\n>> --- a/src/backend/catalog/system_views.sql\n>> +++ b/src/backend/catalog/system_views.sql\n>> @@ -555,10 +555,10 @@ REVOKE ALL ON pg_shmem_allocations FROM PUBLIC;\n>> REVOKE EXECUTE ON FUNCTION pg_get_shmem_allocations() FROM PUBLIC;\n>> \n>> CREATE VIEW pg_backend_memory_contexts AS\n>> - SELECT * FROM pg_get_backend_memory_contexts();\n>> + SELECT * FROM pg_get_backend_memory_contexts(-1);\n> \n> -1 is odd. Why not use NULL or even 0?\n> \n>> +\telse\n>> +\t{\n>> +\t\tint\t\t\trc;\n>> +\t\tint parent_len = strlen(parent);\n>> +\t\tint name_len = strlen(name);\n>> +\n>> +\t\t/*\n>> +\t\t * write out the current memory context information.\n>> +\t\t * Since some elements of values are reusable, we write it out.\n> \n> Not sure what the second comment line here is supposed to mean?\n> \n> \n>> +\t\t */\n>> +\t\tfputc('D', fpout);\n>> +\t\trc = fwrite(values, sizeof(values), 1, fpout);\n>> +\t\trc = fwrite(nulls, sizeof(nulls), 1, fpout);\n>> +\n>> +\t\t/* write out information which is not resuable from serialized \n>> values */\n> \n> s/resuable/reusable/\n> \n> \n>> +\t\trc = fwrite(&name_len, sizeof(int), 1, fpout);\n>> +\t\trc = fwrite(name, name_len, 1, fpout);\n>> +\t\trc = fwrite(&idlen, sizeof(int), 1, fpout);\n>> +\t\trc = fwrite(clipped_ident, idlen, 1, fpout);\n>> +\t\trc = fwrite(&level, sizeof(int), 1, fpout);\n>> +\t\trc = fwrite(&parent_len, sizeof(int), 1, fpout);\n>> +\t\trc = fwrite(parent, parent_len, 1, fpout);\n>> +\t\t(void) rc;\t\t\t\t/* we'll check for error with ferror */\n>> +\n>> +\t}\n> \n> This format is not descriptive. How about serializing to json or\n> something? Or at least having field names?\n> \n> Alternatively, build the same tuple we build for the SRF, and serialize\n> that. Then there's basically no conversion needed.\n> \n> \n>> @@ -117,6 +157,8 @@ PutMemoryContextsStatsTupleStore(Tuplestorestate \n>> *tupstore,\n>> Datum\n>> pg_get_backend_memory_contexts(PG_FUNCTION_ARGS)\n>> {\n>> +\tint\t\t\tpid = PG_GETARG_INT32(0);\n>> +\n>> \tReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;\n>> \tTupleDesc\ttupdesc;\n>> \tTuplestorestate *tupstore;\n>> @@ -147,11 +189,258 @@ \n>> pg_get_backend_memory_contexts(PG_FUNCTION_ARGS)\n>> \n>> \tMemoryContextSwitchTo(oldcontext);\n>> \n>> -\tPutMemoryContextsStatsTupleStore(tupstore, tupdesc,\n>> -\t\t\t\t\t\t\t\tTopMemoryContext, NULL, 0);\n>> +\tif (pid == -1)\n>> +\t{\n>> +\t\t/*\n>> +\t\t * Since pid -1 indicates target is the local process, simply\n>> +\t\t * traverse memory contexts.\n>> +\t\t */\n>> +\t\tPutMemoryContextsStatsTupleStore(tupstore, tupdesc,\n>> +\t\t\t\t\t\t\t\tTopMemoryContext, \"\", 0, NULL);\n>> +\t}\n>> +\telse\n>> +\t{\n>> +\t\t/*\n>> +\t\t * Send signal for dumping memory contexts to the target process,\n>> +\t\t * and read the dumped file.\n>> +\t\t */\n>> +\t\tFILE\t *fpin;\n>> +\t\tchar\t\tdumpfile[MAXPGPATH];\n>> +\n>> +\t\tSendProcSignal(pid, PROCSIG_DUMP_MEMORY, InvalidBackendId);\n>> +\n>> +\t\tsnprintf(dumpfile, sizeof(dumpfile), \"pg_memusage/%d\", pid);\n>> +\n>> +\t\twhile (true)\n>> +\t\t{\n>> +\t\t\tCHECK_FOR_INTERRUPTS();\n>> +\n>> +\t\t\tpg_usleep(10000L);\n>> +\n> \n> Need better signalling back/forth here.\n\nDo you mean I should also send another signal from the dumped\nprocess to the caller of the pg_get_backend_memory_contexts()\nwhen it finishes dumping?\n\nRegards,\n\n\n\n--\nAtsushi Torikoshi\nNTT DATA CORPORATION\n\n> \n> \n> \n>> +/*\n>> + * dump_memory_contexts\n>> + * \tDumping local memory contexts to a file.\n>> + * \tThis function does not delete the file as it is intended to be \n>> read by\n>> + * \tanother process.\n>> + */\n>> +static void\n>> +dump_memory_contexts(void)\n>> +{\n>> +\tFILE\t *fpout;\n>> +\tchar\t\ttmpfile[MAXPGPATH];\n>> +\tchar\t\tdumpfile[MAXPGPATH];\n>> +\n>> +\tsnprintf(tmpfile, sizeof(tmpfile), \"pg_memusage/%d.tmp\", MyProcPid);\n>> +\tsnprintf(dumpfile, sizeof(dumpfile), \"pg_memusage/%d\", MyProcPid);\n>> +\n>> +\t/*\n>> +\t * Open a temp file to dump the current memory context.\n>> +\t */\n>> +\tfpout = AllocateFile(tmpfile, PG_BINARY_W);\n>> +\tif (fpout == NULL)\n>> +\t{\n>> +\t\tereport(LOG,\n>> +\t\t\t\t(errcode_for_file_access(),\n>> +\t\t\t\t errmsg(\"could not write temporary memory context file \\\"%s\\\": \n>> %m\",\n>> +\t\t\t\t\t\ttmpfile)));\n>> +\t\treturn;\n>> +\t}\n> \n> Probably should be opened with O_CREAT | O_TRUNC?\n> \n> \n> Greetings,\n> \n> Andres Freund\n\n\n", "msg_date": "Thu, 03 Sep 2020 15:40:00 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "Hi,\n\nOn Thu, Sep 3, 2020 at 3:38 PM torikoshia <torikoshia@oss.nttdata.com> wrote:\n> >> - Currently, \"the signal transmission for dumping memory\n> >> information\"\n> >> and \"the read & output of dump information \"\n> >> are on the same interface, but I think it would be better to\n> >> separate them.\n> >> How about providing the following three types of functions for\n> >> users?\n> >> - send a signal to specified pid\n> >> - check the status of the signal sent and received\n> >> - read the dumped information\n>\n> Is this for future extensibility to make it possible to get\n> other information like the current execution plan which was\n> suggested by Pavel?\nYes, but it's not only for future expansion, but also for the\nusability and the stability of this feature.\nFor example, if you want to read one dumped file multiple times and analyze it,\nyou will want the ability to just read the dump.\nMoreover, when it takes a long time from the receive the signal to the\ndump output,\nor the dump output itself takes a long time, users can investigate\nwhere it takes time\nif each process is separated.\n\n> If so, I agree with considering extensibility, but I'm not\n> sure it's necessary whether providing these types of\n> functions for 'users'.\nOf course, it is possible and may be necessary to provide a wrapped\nsequence of processes\nfrom sending a signal to reading dump files.\nBut IMO, some users would like to perform the signal transmission,\nstate management and\ndump file reading processes separately.\n\nBest regards,\n\n-- \nTatsuhito Kasahara\nkasahara.tatsuhito _at_ gmail.com\n\n\n", "msg_date": "Fri, 4 Sep 2020 02:18:15 +0900", "msg_from": "Kasahara Tatsuhito <kasahara.tatsuhito@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "Kasahara Tatsuhito <kasahara.tatsuhito@gmail.com> writes:\n> Yes, but it's not only for future expansion, but also for the\n> usability and the stability of this feature.\n> For example, if you want to read one dumped file multiple times and analyze it,\n> you will want the ability to just read the dump.\n\nIf we design it to make that possible, how are we going to prevent disk\nspace leaks from never-cleaned-up dump files?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 03 Sep 2020 13:40:07 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On Fri, Sep 4, 2020 at 2:40 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Kasahara Tatsuhito <kasahara.tatsuhito@gmail.com> writes:\n> > Yes, but it's not only for future expansion, but also for the\n> > usability and the stability of this feature.\n> > For example, if you want to read one dumped file multiple times and analyze it,\n> > you will want the ability to just read the dump.\n>\n> If we design it to make that possible, how are we going to prevent disk\n> space leaks from never-cleaned-up dump files?\nIn my thought, with features such as a view that allows us to see a\nlist of dumped files,\nit would be better to have a function that simply deletes the dump\nfiles associated with a specific PID,\nor to delete all dump files.\nSome files may be dumped with unexpected delays, so I think the\ncleaning feature will be necessary.\n( Also, as the pgsql_tmp file, it might better to delete dump files\nwhen PostgreSQL start.)\n\nOr should we try to delete the dump file as soon as we can read it?\n\nBest regards,\n\n-- \nTatsuhito Kasahara\nkasahara.tatsuhito _at_ gmail.com\n\n\n", "msg_date": "Fri, 4 Sep 2020 11:47:30 +0900", "msg_from": "Kasahara Tatsuhito <kasahara.tatsuhito@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On Fri, Sep 04, 2020 at 11:47:30AM +0900, Kasahara Tatsuhito wrote:\n>On Fri, Sep 4, 2020 at 2:40 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> Kasahara Tatsuhito <kasahara.tatsuhito@gmail.com> writes:\n>> > Yes, but it's not only for future expansion, but also for the\n>> > usability and the stability of this feature.\n>> > For example, if you want to read one dumped file multiple times and analyze it,\n>> > you will want the ability to just read the dump.\n>>\n>> If we design it to make that possible, how are we going to prevent disk\n>> space leaks from never-cleaned-up dump files?\n>In my thought, with features such as a view that allows us to see a\n>list of dumped files,\n>it would be better to have a function that simply deletes the dump\n>files associated with a specific PID,\n>or to delete all dump files.\n>Some files may be dumped with unexpected delays, so I think the\n>cleaning feature will be necessary.\n>( Also, as the pgsql_tmp file, it might better to delete dump files\n>when PostgreSQL start.)\n>\n>Or should we try to delete the dump file as soon as we can read it?\n>\n\nIMO making the cleanup a responsibility of the users (e.g. by exposing\nthe list of dumped files through a view and expecting users to delete\nthem in some way) is rather fragile.\n\nI don't quite see what's the point of designing it this way. It was\nsuggested this improves stability and usability of this feature, but\nsurely making it unnecessarily complex contradicts both points?\n\nIMHO if the user needs to process the dump repeatedly, what's preventing\nhim/her from storing it in a file, or something like that? At that point\nit's clear it's up to them to remove the file. So I suggest to keep the\nfeature as simple as possible - hand the dump over and delete.\n\n\nregards\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 4 Sep 2020 14:46:19 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On 2020-09-04 21:46, Tomas Vondra wrote:\n> On Fri, Sep 04, 2020 at 11:47:30AM +0900, Kasahara Tatsuhito wrote:\n>> On Fri, Sep 4, 2020 at 2:40 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>>> Kasahara Tatsuhito <kasahara.tatsuhito@gmail.com> writes:\n>>> > Yes, but it's not only for future expansion, but also for the\n>>> > usability and the stability of this feature.\n>>> > For example, if you want to read one dumped file multiple times and analyze it,\n>>> > you will want the ability to just read the dump.\n>>> \n>>> If we design it to make that possible, how are we going to prevent \n>>> disk\n>>> space leaks from never-cleaned-up dump files?\n>> In my thought, with features such as a view that allows us to see a\n>> list of dumped files,\n>> it would be better to have a function that simply deletes the dump\n>> files associated with a specific PID,\n>> or to delete all dump files.\n>> Some files may be dumped with unexpected delays, so I think the\n>> cleaning feature will be necessary.\n>> ( Also, as the pgsql_tmp file, it might better to delete dump files\n>> when PostgreSQL start.)\n>> \n>> Or should we try to delete the dump file as soon as we can read it?\n>> \n> \n> IMO making the cleanup a responsibility of the users (e.g. by exposing\n> the list of dumped files through a view and expecting users to delete\n> them in some way) is rather fragile.\n> \n> I don't quite see what's the point of designing it this way. It was\n> suggested this improves stability and usability of this feature, but\n> surely making it unnecessarily complex contradicts both points?\n> \n> IMHO if the user needs to process the dump repeatedly, what's \n> preventing\n> him/her from storing it in a file, or something like that? At that \n> point\n> it's clear it's up to them to remove the file. So I suggest to keep the\n> feature as simple as possible - hand the dump over and delete.\n\n+1.\nIf there are no other objections, I'm going to accept this\nsuggestion.\n\nRegards\n\n\n", "msg_date": "Thu, 10 Sep 2020 20:53:53 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "Hi,\n\nOn Thu, Sep 10, 2020 at 8:53 PM torikoshia <torikoshia@oss.nttdata.com> wrote:\n>\n> On 2020-09-04 21:46, Tomas Vondra wrote:\n> > On Fri, Sep 04, 2020 at 11:47:30AM +0900, Kasahara Tatsuhito wrote:\n> >> On Fri, Sep 4, 2020 at 2:40 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >>> Kasahara Tatsuhito <kasahara.tatsuhito@gmail.com> writes:\n> >>> > Yes, but it's not only for future expansion, but also for the\n> >>> > usability and the stability of this feature.\n> >>> > For example, if you want to read one dumped file multiple times and analyze it,\n> >>> > you will want the ability to just read the dump.\n> >>>\n> >>> If we design it to make that possible, how are we going to prevent\n> >>> disk\n> >>> space leaks from never-cleaned-up dump files?\n> >> In my thought, with features such as a view that allows us to see a\n> >> list of dumped files,\n> >> it would be better to have a function that simply deletes the dump\n> >> files associated with a specific PID,\n> >> or to delete all dump files.\n> >> Some files may be dumped with unexpected delays, so I think the\n> >> cleaning feature will be necessary.\n> >> ( Also, as the pgsql_tmp file, it might better to delete dump files\n> >> when PostgreSQL start.)\n> >>\n> >> Or should we try to delete the dump file as soon as we can read it?\n> >>\n> >\n> > IMO making the cleanup a responsibility of the users (e.g. by exposing\n> > the list of dumped files through a view and expecting users to delete\n> > them in some way) is rather fragile.\n> >\n> > I don't quite see what's the point of designing it this way. It was\n> > suggested this improves stability and usability of this feature, but\n> > surely making it unnecessarily complex contradicts both points?\n> >\n> > IMHO if the user needs to process the dump repeatedly, what's\n> > preventing\n> > him/her from storing it in a file, or something like that? At that\n> > point\n> > it's clear it's up to them to remove the file. So I suggest to keep the\n> > feature as simple as possible - hand the dump over and delete.\nYeah, it might be better to avoid making the user responsible for removal.\n\nI think it's fine to have an interface to delete in an emergency, but\nI agree that\nusers shouldn't be made aware of the existence or deletion of dump\nfiles, basically.\n\n> +1.\n> If there are no other objections, I'm going to accept this\n> suggestion.\nSo +1\n\nBest regards,\n\n-- \nTatsuhito Kasahara\nkasahara.tatsuhito _at_ gmail.com\n\n\n", "msg_date": "Thu, 10 Sep 2020 21:11:21 +0900", "msg_from": "Kasahara Tatsuhito <kasahara.tatsuhito@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On Thu, Sep 10, 2020 at 09:11:21PM +0900, Kasahara Tatsuhito wrote:\n> I think it's fine to have an interface to delete in an emergency, but\n> I agree that\n> users shouldn't be made aware of the existence or deletion of dump\n> files, basically.\n\nPer the CF bot, the number of tests needs to be tweaked, because we\ntest each entry filtered out with is_deeply(), meaning that the number\nof tests needs to be updated to reflect that if the filtered list is\nchanged:\nt/010_pg_basebackup.pl ... 104/109 # Looks like you planned 109 tests but ran 110.\nt/010_pg_basebackup.pl ... Dubious, test returned 255 (wstat 65280, 0xff00)\nAll 109 subtests passed\n\nSimple enough to fix.\n--\nMichael", "msg_date": "Thu, 24 Sep 2020 13:01:49 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "Hi,\n\nThanks for all your comments, I updated the patch.\n\n\nOn Tue, Sep 1, 2020 at 12:03 AM Kasahara Tatsuhito \n<kasahara.tatsuhito@gmail.com> wrote:\n\n> - How about managing the status of signal send/receive and dump\n> operations on a shared hash or others ?\n> Sending and receiving signals, dumping memory information, and\n> referencing dump information all work asynchronously.\n> Therefore, it would be good to have management information to\n> check\n> the status of each process.\n> A simple idea is that ..\n> - send a signal to dump to a PID, it first record following\n> information into the shared hash.\n> pid (specified pid)\n> loc (dump location, currently might be ASAP)\n> recv (did the pid process receive a signal? first false)\n> dumped (did the pid process dump a mem information? first\n> false)\n> - specified process receive the signal, update the status in the\n> shared hash, then dumped at specified location.\n> - specified process finish dump mem information, update the\n> status\n> in the shared hash.\n\nI added a shared hash table consisted of minimal members\nmainly for managing whether the file is dumped or not.\nSome members like 'loc' seem useful in the future, but I\nhaven't added them since it's not essential at this point.\n\n\n\nOn 2020-09-01 10:54, Andres Freund wrote:\n\n>> CREATE VIEW pg_backend_memory_contexts AS\n>> - SELECT * FROM pg_get_backend_memory_contexts();\n>> + SELECT * FROM pg_get_backend_memory_contexts(-1);\n> \n> -1 is odd. Why not use NULL or even 0?\n\nChanged it from -1 to NULL.\n\n>> + rc = fwrite(&name_len, sizeof(int), 1, fpout);\n>> + rc = fwrite(name, name_len, 1, fpout);\n>> + rc = fwrite(&idlen, sizeof(int), 1, fpout);\n>> + rc = fwrite(clipped_ident, idlen, 1, fpout);\n>> + rc = fwrite(&level, sizeof(int), 1, fpout);\n>> + rc = fwrite(&parent_len, sizeof(int), 1, fpout);\n>> + rc = fwrite(parent, parent_len, 1, fpout);\n>> + (void) rc; /* we'll check \n>> for error with ferror */\n>> +\n>> + }\n> This format is not descriptive. How about serializing to json or\n> something? Or at least having field names?\n\nAdded field names for each value.\n\n>> + while (true)\n>> + {\n>> + CHECK_FOR_INTERRUPTS();\n>> +\n>> + pg_usleep(10000L);\n>> +\n> \n> Need better signalling back/forth here.\n\nAdded a shared hash table that has a flag for managing whether the file \nis dumped or not.\nI modified it to use this flag.\n\n>> + /*\n>> + * Open a temp file to dump the current memory context.\n>> + */\n>> + fpout = AllocateFile(tmpfile, PG_BINARY_W);\n>> + if (fpout == NULL)\n>> + {\n>> + ereport(LOG,\n>> + (errcode_for_file_access(),\n>> + errmsg(\"could not write temporary \n>> memory context file \\\"%s\\\": %m\",\n>> + tmpfile)));\n>> + return;\n>> + }\n> \n> Probably should be opened with O_CREAT | O_TRUNC?\n\nAllocateFile() calls fopen() and AFAIU fopen() with mode \"w\" corresponds \nto open() with \"O_WRONLY | O_CREAT | O_TRUNC\".\n\nDo you mean I should not use fopen() here?\n\nOn 2020-09-24 13:01, Michael Paquier wrote:\n> On Thu, Sep 10, 2020 at 09:11:21PM +0900, Kasahara Tatsuhito wrote:\n>> I think it's fine to have an interface to delete in an emergency, but\n>> I agree that\n>> users shouldn't be made aware of the existence or deletion of dump\n>> files, basically.\n> \n> Per the CF bot, the number of tests needs to be tweaked, because we\n> test each entry filtered out with is_deeply(), meaning that the number\n> of tests needs to be updated to reflect that if the filtered list is\n> changed:\n> t/010_pg_basebackup.pl ... 104/109 # Looks like you planned 109 tests\n> but ran 110.\n> t/010_pg_basebackup.pl ... Dubious, test returned 255 (wstat 65280, \n> 0xff00)\n> All 109 subtests passed\n> \n> Simple enough to fix.\n\nIncremented the number of tests.\n\n\nAny thoughts?\n\nRegards,\n\n-- \nAtsushi Torikoshi\nNTT DATA CORPORATION", "msg_date": "Fri, 25 Sep 2020 16:28:02 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "Hi,\n\nOn Fri, Sep 25, 2020 at 4:28 PM torikoshia <torikoshia@oss.nttdata.com> wrote:\n> Thanks for all your comments, I updated the patch.\nThanks for updating the patch.\nI did a brief test and code review.\n\n> I added a shared hash table consisted of minimal members\n> mainly for managing whether the file is dumped or not.\n> Some members like 'loc' seem useful in the future, but I\n> haven't added them since it's not essential at this point.\nYes, that would be good.\n\n+ /*\n+ * Since we allow only one session can request to dump\nmemory context at\n+ * the same time, check whether the dump files already exist.\n+ */\n+ while (stat(dumpfile, &stat_tmp) == 0 || stat(tmpfile, &stat_tmp) == 0)\n+ {\n+ pg_usleep(1000000L);\n+ }\n\nIf pg_get_backend_memory_contexts() is executed by two or more\nsessions at the same time, it cannot be run exclusively in this way.\nCurrently it seems to cause a crash when do it so.\nThis is easy to reproduce and can be done as follows.\n\n[session-1]\nBEGIN;\nLOCK TABKE t1;\n [Session-2]\n BEGIN;\n LOCK TABLE t1; <- waiting\n [Session-3]\n select * FROM pg_get_backend_memory_contexts(<pid of session-2>);\n [Session-4]\n select * FROM pg_get_backend_memory_contexts(<pid of session-2>);\n\nIf you issue commit or abort at session-1, you will get SEGV.\n\nInstead of checking for the existence of the file, it might be better\nto use a hash (mcxtdumpHash) entry with LWLock.\n\n+ if (proc == NULL)\n+ {\n+ ereport(WARNING,\n+ (errmsg(\"PID %d is not a PostgreSQL server\nprocess\", dst_pid)));\n+ return (Datum) 1;\n+ }\n\nShouldn't it clear the hash entry before return?\n\n+ /* Wait until target process finished dumping file. */\n+ while (!entry->is_dumped)\n+ {\n+ CHECK_FOR_INTERRUPTS();\n+ pg_usleep(10000L);\n+ }\n\nIf the target is killed and exit before dumping the memory\ninformation, you're in an infinite loop here.\nSo how about making sure that any process that has to stop before\ndoing a memory dump changes the status of the hash (entry->is_dumped)\nbefore stopping and the caller detects it?\nI'm not sure it's best or not, but you might want to use something\nlike the on_shmem_exit callback.\n\nIn the current design, if the caller stops processing before reading\nthe dumped file, you will have an orphaned file.\nIt looks like the following.\n\n[session-1]\nBEGIN;\nLOCK TABKE t1;\n [Session-2]\n BEGIN;\n LOCK TABLE t1; <- waiting\n [Session-3]\n select * FROM pg_get_backend_memory_contexts(<pid of session-2>);\n\nIf you cancel or terminate the session-3, then issue commit or abort\nat session-1, you will get orphaned files in pg_memusage.\n\nSo if you allow only one session can request to dump file, it could\ncall pg_memusage_reset() before send the signal in this function.\n\nBest regards,\n\n--\nTatsuhito Kasahara\nkasahara.tatsuhito _at_ gmail.com\n\n\n", "msg_date": "Thu, 1 Oct 2020 16:06:23 +0900", "msg_from": "Kasahara Tatsuhito <kasahara.tatsuhito@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "> On Thu, Oct 1, 2020 at 4:06 PM Kasahara Tatsuhito \n> <kasahara.tatsuhito@gmail.com> wrote:\n> Hi,\n> \n> On Fri, Sep 25, 2020 at 4:28 PM torikoshia <torikoshia@oss.nttdata.com> \n> wrote:\n> > Thanks for all your comments, I updated the patch.\n> Thanks for updating the patch.\n> I did a brief test and code review.\n\nThanks for your tests and review!\n\n> > I added a shared hash table consisted of minimal members\n> > mainly for managing whether the file is dumped or not.\n> > Some members like 'loc' seem useful in the future, but I\n> > haven't added them since it's not essential at this point.\n> Yes, that would be good.\n> \n> +        /*\n> +         * Since we allow only one session can request to dump\n> memory context at\n> +         * the same time, check whether the dump files already exist.\n> +         */\n> +        while (stat(dumpfile, &stat_tmp) == 0 || stat(tmpfile, \n> &stat_tmp) == 0)\n> +        {\n> +            pg_usleep(1000000L);\n> +        }\n> \n> If pg_get_backend_memory_contexts() is executed by two or more\n> sessions at the same time, it cannot be run exclusively in this way.\n> Currently it seems to cause a crash when do it so.\n> This is easy to reproduce and can be done as follows.\n> \n> [session-1]\n> BEGIN;\n> LOCK TABKE t1;\n>   [Session-2]\n>   BEGIN;\n>   LOCK TABLE t1; <- waiting\n>     [Session-3]\n>     select * FROM pg_get_backend_memory_contexts(<pid of session-2>);\n>       [Session-4]\n>       select * FROM pg_get_backend_memory_contexts(<pid of session-2>);\n> \n> If you issue commit or abort at session-1, you will get SEGV.\n> \n> Instead of checking for the existence of the file, it might be better\n> to use a hash (mcxtdumpHash) entry with LWLock.\n\nThanks!\nAdded a LWLock and changed the way from checking the file existence\nto finding the hash entry.\n\n> +        if (proc == NULL)\n> +        {\n> +            ereport(WARNING,\n> +                    (errmsg(\"PID %d is not a PostgreSQL server\n> process\", dst_pid)));\n> +            return (Datum) 1;\n> +        }\n> \n> Shouldn't it clear the hash entry before return?\n\nYeah. added codes for removing the entry.\n\n> \n> +        /* Wait until target process finished dumping file. */\n> +        while (!entry->is_dumped)\n> +        {\n> +            CHECK_FOR_INTERRUPTS();\n> +            pg_usleep(10000L);\n> +        }\n> \n> If the target is killed and exit before dumping the memory\n> information, you're in an infinite loop here.\n> So how about making sure that any process that has to stop before\n> doing a memory dump changes the status of the hash (entry->is_dumped)\n> before stopping and the caller detects it?\n> I'm not sure it's best or not, but you might want to use something\n> like the on_shmem_exit callback.\n\nThanks for your idea!\nAdded a callback to change the status of the hash table entry.\n\nAlthough I think it's necessary to remove this callback when it finished\nprocessing memory dumping, on_shmem_exit() does not seem to have such\na function.\nI used before_shmem_exit() since it has a corresponding function to\nremove registered callback.\nIf it's inappropriate, I'm going to add a function removing the\nregistered callback of on_shmem_exit().\n\n> In the current design, if the caller stops processing before reading\n> the dumped file, you will have an orphaned file.\n> It looks like the following.\n> \n> [session-1]\n> BEGIN;\n> LOCK TABKE t1;\n>   [Session-2]\n>   BEGIN;\n>   LOCK TABLE t1; <- waiting\n>     [Session-3]\n>     select * FROM pg_get_backend_memory_contexts(<pid of session-2>);\n> \n> If you cancel or terminate the session-3, then issue commit or abort\n> at session-1, you will get orphaned files in pg_memusage.\n> \n> So if you allow only one session can request to dump file, it could\n> call pg_memusage_reset() before send the signal in this function.\n\nAlthough I'm going to allow only one session per one target process,\nI'd like to allow running multiple pg_get_backend_memory_contexts()\nwhich target process is different.\n\nInstead of calling pg_memusage_reset(), I added a callback for\ncleaning up orphaned files and the elements of the hash table\nusing before_shmem_exit() through PG_ENSURE_ERROR_CLEANUP() and\nPG_END_ENSURE_ERROR_CLEANUP().\n\nI chose PG_ENSURE_ERROR_CLEANUP() and PG_END_ENSURE_ERROR_CLEANUP()\nhere since it can handle not only termination but also cancellation.\n\nAny thoughts?\n\n\n-- \nAtsushi Torikoshi", "msg_date": "Thu, 22 Oct 2020 21:32:00 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "Wait...\n\n> Attachments: 0003-Enabled-pg_get_backend_memory_contexts-to-collect.patch\n\nFor a moment I thought that the number is patch number but the\npredecessors are 0002-Enabled..collect.patch and 0001-(same\nname). It's not mandatory but we usually do as the follows and it's\nthe way of git.\n\nv1-0001-Enabled...collect.patch\nv2-0001-Enabled...collect.patch\n\nThe vn is added by -v option for git-format-patch.\n\nAt Thu, 22 Oct 2020 21:32:00 +0900, torikoshia <torikoshia@oss.nttdata.com> wrote in \n> > > I added a shared hash table consisted of minimal members\n> > > mainly for managing whether the file is dumped or not.\n> > > Some members like 'loc' seem useful in the future, but I\n> > > haven't added them since it's not essential at this point.\n> > Yes, that would be good.\n> > +        /*\n> > +         * Since we allow only one session can request to dump\n> > memory context at\n> > +         * the same time, check whether the dump files already exist.\n> > +         */\n> > +        while (stat(dumpfile, &stat_tmp) == 0 || stat(tmpfile,\n> > &stat_tmp) == 0)\n> > +        {\n> > +            pg_usleep(1000000L);\n> > +        }\n> > If pg_get_backend_memory_contexts() is executed by two or more\n> > sessions at the same time, it cannot be run exclusively in this way.\n> > Currently it seems to cause a crash when do it so.\n> > This is easy to reproduce and can be done as follows.\n> > [session-1]\n> > BEGIN;\n> > LOCK TABKE t1;\n> >   [Session-2]\n> >   BEGIN;\n> >   LOCK TABLE t1; <- waiting\n> >     [Session-3]\n> >     select * FROM pg_get_backend_memory_contexts(<pid of session-2>);\n> >       [Session-4]\n> >       select * FROM pg_get_backend_memory_contexts(<pid of\n> > session-2>);\n> > If you issue commit or abort at session-1, you will get SEGV.\n> > Instead of checking for the existence of the file, it might be better\n> > to use a hash (mcxtdumpHash) entry with LWLock.\n> \n> Thanks!\n> Added a LWLock and changed the way from checking the file existence\n> to finding the hash entry.\n\n> > +        if (proc == NULL)\n> > +        {\n> > +            ereport(WARNING,\n> > +                    (errmsg(\"PID %d is not a PostgreSQL server\n> > process\", dst_pid)));\n> > +            return (Datum) 1;\n> > +        }\n> > Shouldn't it clear the hash entry before return?\n> \n> Yeah. added codes for removing the entry.\n\n+\t\tentry = AddEntryToMcxtdumpHash(dst_pid);\n+\n+\t\t/* Check whether the target process is PostgreSQL backend process. */\n+\t\t/* TODO: Check also whether backend or not. */\n+\t\tproc = BackendPidGetProc(dst_pid);\n+\n+\t\tif (proc == NULL)\n+\t\t{\n+\t\t\tereport(WARNING,\n+\t\t\t\t\t(errmsg(\"PID %d is not a PostgreSQL server process\", dst_pid)));\n+\n+\t\t\tLWLockAcquire(McxtDumpHashLock, LW_EXCLUSIVE);\n+\n+\t\t\tif (hash_search(mcxtdumpHash, &dst_pid, HASH_REMOVE, NULL) == NULL)\n+\t\t\t\telog(WARNING, \"hash table corrupted\");\n+\n+\t\t\tLWLockRelease(McxtDumpHashLock);\n+\n+\t\t\treturn (Datum) 1;\n+\t\t}\n\nWhy do you enter a useles entry then remove it immedately?\n\n+\t\tPG_ENSURE_ERROR_CLEANUP(McxtReqKill, (Datum) Int32GetDatum(dst_pid));\n+\t\t{\n+\t\t\tSendProcSignal(dst_pid, PROCSIG_DUMP_MEMORY, InvalidBackendId);\n\n\"PROCSIG_DUMP_MEMORY\" is somewhat misleading. Hwo about\n\"PROCSIG_DUMP_MEMCXT\" or \"PROCSIG_DUMP_MEMORY_CONTEXT\"?\n\nI thought that the hash table would prevent multiple reqestors from\nmaking a request at once, but the patch doesn't seem to do that.\n\n+\t\t\t/* Wait until target process finished dumping file. */\n+\t\t\twhile (entry->dump_status == MCXTDUMPSTATUS_NOTYET)\n\nThis needs LWLock. And this could read the entry after reused by\nanother backend if the dumper process is gone. That isn't likely to\nhappen, but theoretically the other backend may set it to\nMCXTDUMPSTATUS_NOTYET inbetween two successive check on the member.\n\n+\t/*\n+\t * Make dump file ends with 'D'.\n+\t * This is checked by the caller when reading the file.\n+\t */\n+\tfputc('E', fpout);\n\nWhich is right?\n\n+\tfputc('E', fpout);\n+\n+\tCHECK_FOR_INTERRUPTS();\n\nThis means that the process accepts another request and rewrite the\nfile even while the first requester is reading it. And, the file can\nbe removed by the first requestor before the second requestor can read\nit.\n\n+\tmcxtdumpHash = ShmemInitHash(\"mcxtdump hash\",\n+\t\t\t\t\t\t\t SHMEM_MEMCONTEXT_SIZE,\n+\t\t\t\t\t\t\t SHMEM_MEMCONTEXT_SIZE,\n\nThe space needed for this hash doesn't seem to be secured. The hash is\nsized to 64 entries, so pg_get_backend_memory_contexts() may fail with\nERROR \"out of shared memory\".\n\nThe hash is used only to check if the dump file is completed and if\nended with error. If we need only those, an shared byte array with the\nlength of max_backend is sufficient.\n\n+\t\tPG_ENSURE_ERROR_CLEANUP(McxtReqKill, (Datum) Int32GetDatum(dst_pid));\n+\t\t{\n+\t\t\tSendProcSignal(dst_pid, PROCSIG_DUMP_MEMORY, InvalidBackendId);\n+\n+\t\t\t/* Wait until target process finished dumping file. */\n+\t\t\twhile (entry->dump_status == MCXTDUMPSTATUS_NOTYET)\n+\t\t\t{\n+\t\t\t\tCHECK_FOR_INTERRUPTS();\n+\t\t\t\tpg_usleep(10000L);\n+\t\t\t}\n+\t\t}\n+\t\tPG_END_ENSURE_ERROR_CLEANUP(McxtReqKill, (Datum) Int32GetDatum(dst_pid));\n+\n+\t\tif (entry->dump_status == MCXTDUMPSTATUS_ERROR)\n+\t\t{\n..\n+\t\t\tif (stat(tmpfile, &stat_tmp) == 0)\n+\t\t\t\tunlink(tmpfile);\n+\t\t\tif (stat(dumpfile, &stat_tmp) == 0)\n+\t\t\t\tunlink(dumpfile);\n...\n+\t\t\treturn (Datum) 0;\n+\t\t}\n+\n+\t\t/* Read values from the dumped file and put them on tuplestore. */\n+\t\tPutDumpedValuesOnTuplestore(dumpfile, tupstore, tupdesc, dst_pid);\n\nThis means that if the function gets sigint before the dumper creates\nthe file, the dumper can leave a dump file?\n\n> > +        /* Wait until target process finished dumping file. */\n> > +        while (!entry->is_dumped)\n> > +        {\n> > +            CHECK_FOR_INTERRUPTS();\n> > +            pg_usleep(10000L);\n> > +        }\n> > If the target is killed and exit before dumping the memory\n> > information, you're in an infinite loop here.\n> > So how about making sure that any process that has to stop before\n> > doing a memory dump changes the status of the hash (entry->is_dumped)\n> > before stopping and the caller detects it?\n> > I'm not sure it's best or not, but you might want to use something\n> > like the on_shmem_exit callback.\n> \n> Thanks for your idea!\n> Added a callback to change the status of the hash table entry.\n> \n> Although I think it's necessary to remove this callback when it\n> finished\n> processing memory dumping, on_shmem_exit() does not seem to have such\n> a function.\n> I used before_shmem_exit() since it has a corresponding function to\n> remove registered callback.\n> If it's inappropriate, I'm going to add a function removing the\n> registered callback of on_shmem_exit().\n\nThis seems to leave a file for the pid.\n\n> > In the current design, if the caller stops processing before reading\n> > the dumped file, you will have an orphaned file.\n> > It looks like the following.\n> > [session-1]\n> > BEGIN;\n> > LOCK TABKE t1;\n> >   [Session-2]\n> >   BEGIN;\n> >   LOCK TABLE t1; <- waiting\n> >     [Session-3]\n> >     select * FROM pg_get_backend_memory_contexts(<pid of session-2>);\n> > If you cancel or terminate the session-3, then issue commit or abort\n> > at session-1, you will get orphaned files in pg_memusage.\n> > So if you allow only one session can request to dump file, it could\n> > call pg_memusage_reset() before send the signal in this function.\n> \n> Although I'm going to allow only one session per one target process,\n> I'd like to allow running multiple pg_get_backend_memory_contexts()\n> which target process is different.\n> \n> Instead of calling pg_memusage_reset(), I added a callback for\n> cleaning up orphaned files and the elements of the hash table\n> using before_shmem_exit() through PG_ENSURE_ERROR_CLEANUP() and\n> PG_END_ENSURE_ERROR_CLEANUP().\n> \n> I chose PG_ENSURE_ERROR_CLEANUP() and PG_END_ENSURE_ERROR_CLEANUP()\n> here since it can handle not only termination but also cancellation.\n> \n> Any thoughts?\n\n+/*\n+ * pg_memusage_reset\n+ *\t \tRemove the memory context dump files.\n+ */\n+void\n+pg_memusage_reset(int pid)\n\nThe function name seem to represents somewhat different from what it\ndoes.\n\n\nI think we might need to step-back to basic design of this feature\nsince this patch seems to have unhandled corner cases that are\ndifficult to find.\n\n- Dump file lifecycle or state-transition of the dumper\n\n Currently the lifecycle of a dump file, or the state-transition of\n the dumper process doesn't seem to be well defined.\n\n The file is create only by the dumper.\n If the requestor reads the completed file, the reader removes it.\n\n If the dumper receives a cancel request, the dumper removes it if\n any.\n\n Of course dumper removes it if it fails to complete the file.\n\n- Better way of signalling between the requestor and the dumper\n\n I think there's no doubt about request signal.\n \n About the complete signal, currently the requestor polls on a flag\n in a hash entry. I'm wondering if we can get rid of polling. The\n problem on doing that is the lack of a means for a dumper to know\n the requestor. We need to store requestor pid or backend id in the\n shared hash entry.\n\n By the way, about shared hash entry, it uses about 70kB for only 64\n entries so it seems inefficient than a shared array that has\n MaxBackends entries. If we used a following array on shared memory,\n\n struct hoge\n {\n BackendId requestor[MAX_BACKENDS];\n\tint\t\t status[MAX_BACKENDS];\n\tLWLock lock;\n };\n\n This array has the size of 24 * MaxBackends + 16. 24kB for 1000\n backends. It could be on dsm since this feature is not used\n commonly.\n\n\n- The way to cancel a request already made. (or management of the dump\n state transition.)\n\n Cancellation seems to contain some race conditions. But basically\n that could be done by sending a request signal after setting the\n hoge.requestor above to some special value, not needing the third\n type of signal. The special value should be different from the\n initial state, which signals that the process is accepting a new\n request.\n\n As the whole, that would looks like the folloing?\n\n------------------------------------------------------------\nSuccessful request.\n\n Requestor dumper state\n [idle] initial\n [request] -------------------> requestor pid/backendid\n -signal->\n [dumping]\n <-signal-[done]\n [read]\n [done] --------------------> initial\n\n------------------------------------------------------------\nOn failure, the dumper signals with setting state to initial.\n [request] -------------------> requestor pid/backendid\n -signal->\n [dumping]\n\t\t\t\t\t[failed] initial\n <-signal-\n (some other requestor might come meantime.)\n <sees that the requestor is not me>\n [failed]\n\n------------------------------------------------------------\nIf the requestor wants to cancel the request, it sets the state to\n'cancel' then signal.\n\nRequestor dumper state\n [idle] initial\n [request] -------------------> cancel\n <if canceled. clean up>\n [dumping]\n <if canceled. clean up>\n <-signal-[done]\n\n -signal-><try to clean up>\n\n\nOther aspects to cnosider?\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n \n \n\n\n", "msg_date": "Fri, 23 Oct 2020 13:46:11 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On 2020-10-23 13:46, Kyotaro Horiguchi wrote:\n> Wait...\n> \n>> Attachments: \n>> 0003-Enabled-pg_get_backend_memory_contexts-to-collect.patch\n> \n> For a moment I thought that the number is patch number but the\n> predecessors are 0002-Enabled..collect.patch and 0001-(same\n> name). It's not mandatory but we usually do as the follows and it's\n> the way of git.\n> \n> v1-0001-Enabled...collect.patch\n> v2-0001-Enabled...collect.patch\n> \n> The vn is added by -v option for git-format-patch.\n\nSorry for the confusion. I'll follow that way next time.\n\n> At Thu, 22 Oct 2020 21:32:00 +0900, torikoshia\n> <torikoshia@oss.nttdata.com> wrote in\n>> > > I added a shared hash table consisted of minimal members\n>> > > mainly for managing whether the file is dumped or not.\n>> > > Some members like 'loc' seem useful in the future, but I\n>> > > haven't added them since it's not essential at this point.\n>> > Yes, that would be good.\n>> > +        /*\n>> > +         * Since we allow only one session can request to dump\n>> > memory context at\n>> > +         * the same time, check whether the dump files already exist.\n>> > +         */\n>> > +        while (stat(dumpfile, &stat_tmp) == 0 || stat(tmpfile,\n>> > &stat_tmp) == 0)\n>> > +        {\n>> > +            pg_usleep(1000000L);\n>> > +        }\n>> > If pg_get_backend_memory_contexts() is executed by two or more\n>> > sessions at the same time, it cannot be run exclusively in this way.\n>> > Currently it seems to cause a crash when do it so.\n>> > This is easy to reproduce and can be done as follows.\n>> > [session-1]\n>> > BEGIN;\n>> > LOCK TABKE t1;\n>> >   [Session-2]\n>> >   BEGIN;\n>> >   LOCK TABLE t1; <- waiting\n>> >     [Session-3]\n>> >     select * FROM pg_get_backend_memory_contexts(<pid of session-2>);\n>> >       [Session-4]\n>> >       select * FROM pg_get_backend_memory_contexts(<pid of\n>> > session-2>);\n>> > If you issue commit or abort at session-1, you will get SEGV.\n>> > Instead of checking for the existence of the file, it might be better\n>> > to use a hash (mcxtdumpHash) entry with LWLock.\n>> \n>> Thanks!\n>> Added a LWLock and changed the way from checking the file existence\n>> to finding the hash entry.\n> \n>> > +        if (proc == NULL)\n>> > +        {\n>> > +            ereport(WARNING,\n>> > +                    (errmsg(\"PID %d is not a PostgreSQL server\n>> > process\", dst_pid)));\n>> > +            return (Datum) 1;\n>> > +        }\n>> > Shouldn't it clear the hash entry before return?\n>> \n>> Yeah. added codes for removing the entry.\n> \n> +\t\tentry = AddEntryToMcxtdumpHash(dst_pid);\n> +\n> +\t\t/* Check whether the target process is PostgreSQL backend process. \n> */\n> +\t\t/* TODO: Check also whether backend or not. */\n> +\t\tproc = BackendPidGetProc(dst_pid);\n> +\n> +\t\tif (proc == NULL)\n> +\t\t{\n> +\t\t\tereport(WARNING,\n> +\t\t\t\t\t(errmsg(\"PID %d is not a PostgreSQL server process\", dst_pid)));\n> +\n> +\t\t\tLWLockAcquire(McxtDumpHashLock, LW_EXCLUSIVE);\n> +\n> +\t\t\tif (hash_search(mcxtdumpHash, &dst_pid, HASH_REMOVE, NULL) == NULL)\n> +\t\t\t\telog(WARNING, \"hash table corrupted\");\n> +\n> +\t\t\tLWLockRelease(McxtDumpHashLock);\n> +\n> +\t\t\treturn (Datum) 1;\n> +\t\t}\n> \n> Why do you enter a useles entry then remove it immedately?\n\nDo you mean I should check the process existence first\nsince it enables us to skip entering hash entries?\n\n> \n> +\t\tPG_ENSURE_ERROR_CLEANUP(McxtReqKill, (Datum) \n> Int32GetDatum(dst_pid));\n> +\t\t{\n> +\t\t\tSendProcSignal(dst_pid, PROCSIG_DUMP_MEMORY, InvalidBackendId);\n> \n> \"PROCSIG_DUMP_MEMORY\" is somewhat misleading. Hwo about\n> \"PROCSIG_DUMP_MEMCXT\" or \"PROCSIG_DUMP_MEMORY_CONTEXT\"?\n\nI'll go with \"PROCSIG_DUMP_MEMCXT\".\n\n> \n> I thought that the hash table would prevent multiple reqestors from\n> making a request at once, but the patch doesn't seem to do that.\n> \n> +\t\t\t/* Wait until target process finished dumping file. */\n> +\t\t\twhile (entry->dump_status == MCXTDUMPSTATUS_NOTYET)\n> \n> This needs LWLock. And this could read the entry after reused by\n> another backend if the dumper process is gone. That isn't likely to\n> happen, but theoretically the other backend may set it to\n> MCXTDUMPSTATUS_NOTYET inbetween two successive check on the member.\n\nThanks for your notification.\nI'll use an LWLock.\n\n> \n> +\t/*\n> +\t * Make dump file ends with 'D'.\n> +\t * This is checked by the caller when reading the file.\n> +\t */\n> +\tfputc('E', fpout);\n> \n> Which is right?\n\nSorry, the comment was wrong..\n\n> \n> +\tfputc('E', fpout);\n> +\n> +\tCHECK_FOR_INTERRUPTS();\n> \n> This means that the process accepts another request and rewrite the\n> file even while the first requester is reading it. And, the file can\n> be removed by the first requestor before the second requestor can read\n> it.\n\nI added CHECK_FOR_INTERRUPTS() here to make the dump cancellation\npossible, however, considering your indication, it needs to think\nabout a way to handle only the dump cancellation.\n\n> \n> +\tmcxtdumpHash = ShmemInitHash(\"mcxtdump hash\",\n> +\t\t\t\t\t\t\t SHMEM_MEMCONTEXT_SIZE,\n> +\t\t\t\t\t\t\t SHMEM_MEMCONTEXT_SIZE,\n> .\n> The space needed for this hash doesn't seem to be secured. The hash is\n> sized to 64 entries, so pg_get_backend_memory_contexts() may fail with\n> ERROR \"out of shared memory\".\n> \n> The hash is used only to check if the dump file is completed and if\n> ended with error. If we need only those, an shared byte array with the\n> length of max_backend is sufficient.\n\nAlthough there was a comment that controlling dump location may be a\ngood idea, but it also seems possible to include the location \ninformation\nin the struct Hoge you suggested below.\n\nOn Tue, Sep 1, 2020 at 12:03 AM Kasahara Tatsuhito <[hidden email]> \nwrote:\n| - send a signal to dump to a PID, it first record following\ninformation into the shared hash.\n| pid (specified pid)\n| loc (dump location, currently might be ASAP)\n\n\n> \n> +\t\tPG_ENSURE_ERROR_CLEANUP(McxtReqKill, (Datum) \n> Int32GetDatum(dst_pid));\n> +\t\t{\n> +\t\t\tSendProcSignal(dst_pid, PROCSIG_DUMP_MEMORY, InvalidBackendId);\n> +\n> +\t\t\t/* Wait until target process finished dumping file. */\n> +\t\t\twhile (entry->dump_status == MCXTDUMPSTATUS_NOTYET)\n> +\t\t\t{\n> +\t\t\t\tCHECK_FOR_INTERRUPTS();\n> +\t\t\t\tpg_usleep(10000L);\n> +\t\t\t}\n> +\t\t}\n> +\t\tPG_END_ENSURE_ERROR_CLEANUP(McxtReqKill, (Datum) \n> Int32GetDatum(dst_pid));\n> +\n> +\t\tif (entry->dump_status == MCXTDUMPSTATUS_ERROR)\n> +\t\t{\n> ..\n> +\t\t\tif (stat(tmpfile, &stat_tmp) == 0)\n> +\t\t\t\tunlink(tmpfile);\n> +\t\t\tif (stat(dumpfile, &stat_tmp) == 0)\n> +\t\t\t\tunlink(dumpfile);\n> ...\n> +\t\t\treturn (Datum) 0;\n> +\t\t}\n> +\n> +\t\t/* Read values from the dumped file and put them on tuplestore. */\n> +\t\tPutDumpedValuesOnTuplestore(dumpfile, tupstore, tupdesc, dst_pid);\n> \n> This means that if the function gets sigint before the dumper creates\n> the file, the dumper can leave a dump file?\n\nIn that case, the requestor removes the corresponding hash entry in the\ncallback McxtReqKill, then the dumper who can not find the hash entry\ndoes not dump a file.\n\nHowever, I've now noticed that when the requestor gets sigint just\nafter the dumper check, the dump file remains.\n\nIn the current design, only the requestor can remove the dump file,\nbut it seems necessary to allow the dumper to remove it.\n\n\n>> > +        /* Wait until target process finished dumping file. */\n>> > +        while (!entry->is_dumped)\n>> > +        {\n>> > +            CHECK_FOR_INTERRUPTS();\n>> > +            pg_usleep(10000L);\n>> > +        }\n>> > If the target is killed and exit before dumping the memory\n>> > information, you're in an infinite loop here.\n>> > So how about making sure that any process that has to stop before\n>> > doing a memory dump changes the status of the hash (entry->is_dumped)\n>> > before stopping and the caller detects it?\n>> > I'm not sure it's best or not, but you might want to use something\n>> > like the on_shmem_exit callback.\n>> \n>> Thanks for your idea!\n>> Added a callback to change the status of the hash table entry.\n>> \n>> Although I think it's necessary to remove this callback when it\n>> finished\n>> processing memory dumping, on_shmem_exit() does not seem to have such\n>> a function.\n>> I used before_shmem_exit() since it has a corresponding function to\n>> remove registered callback.\n>> If it's inappropriate, I'm going to add a function removing the\n>> registered callback of on_shmem_exit().\n> \n> This seems to leave a file for the pid.\n\nAs mentioned above, there can be a chance to remain files.\n\n> \n>> > In the current design, if the caller stops processing before reading\n>> > the dumped file, you will have an orphaned file.\n>> > It looks like the following.\n>> > [session-1]\n>> > BEGIN;\n>> > LOCK TABKE t1;\n>> >   [Session-2]\n>> >   BEGIN;\n>> >   LOCK TABLE t1; <- waiting\n>> >     [Session-3]\n>> >     select * FROM pg_get_backend_memory_contexts(<pid of session-2>);\n>> > If you cancel or terminate the session-3, then issue commit or abort\n>> > at session-1, you will get orphaned files in pg_memusage.\n>> > So if you allow only one session can request to dump file, it could\n>> > call pg_memusage_reset() before send the signal in this function.\n>> \n>> Although I'm going to allow only one session per one target process,\n>> I'd like to allow running multiple pg_get_backend_memory_contexts()\n>> which target process is different.\n>> \n>> Instead of calling pg_memusage_reset(), I added a callback for\n>> cleaning up orphaned files and the elements of the hash table\n>> using before_shmem_exit() through PG_ENSURE_ERROR_CLEANUP() and\n>> PG_END_ENSURE_ERROR_CLEANUP().\n>> \n>> I chose PG_ENSURE_ERROR_CLEANUP() and PG_END_ENSURE_ERROR_CLEANUP()\n>> here since it can handle not only termination but also cancellation.\n>> \n>> Any thoughts?\n> \n> +/*\n> + * pg_memusage_reset\n> + *\t \tRemove the memory context dump files.\n> + */\n> +void\n> +pg_memusage_reset(int pid)\n> \n> The function name seem to represents somewhat different from what it\n> does.\n\nYeah, It looks like it actually reset the memory.\nI'll rename it to remove_memcxt_file or something.\n\n> \n> I think we might need to step-back to basic design of this feature\n> since this patch seems to have unhandled corner cases that are\n> difficult to find.\n\nAgreed and thanks for writing it down below.\n\n\n> - Dump file lifecycle or state-transition of the dumper\n> \n> Currently the lifecycle of a dump file, or the state-transition of\n> the dumper process doesn't seem to be well defined.\n> \n> The file is create only by the dumper.\n> If the requestor reads the completed file, the reader removes it.\n> \n> If the dumper receives a cancel request, the dumper removes it if\n> any.\n\n\n> \n> Of course dumper removes it if it fails to complete the file.\n> \n> - Better way of signalling between the requestor and the dumper\n> \n> I think there's no doubt about request signal.\n> \n> About the complete signal, currently the requestor polls on a flag\n> in a hash entry. I'm wondering if we can get rid of polling. The\n> problem on doing that is the lack of a means for a dumper to know\n> the requestor. We need to store requestor pid or backend id in the\n> shared hash entry.\n\nAgreed to get rid of polling.\n\nBTW, it seems common to use a latch instead of pg_usleep() to wait until\nsignals arrive as far as I read latch.h.\nI'm now thinking about using a latch here and it would make polling\nremoved.\n\n> By the way, about shared hash entry, it uses about 70kB for only 64\n> entries so it seems inefficient than a shared array that has\n> MaxBackends entries. If we used a following array on shared memory,\n> \n> struct hoge\n> {\n> BackendId requestor[MAX_BACKENDS];\n> \tint\t\t status[MAX_BACKENDS];\n> \tLWLock lock;\n> };\n\nIf the requestor's id is 5 and dumper's id is 10,\nis this struct used like below?\n\n- hoge.requestor[10] = 5\n- Both status[5] and status[10] change like \"request\", \"idle\" or \"done\"\n\n> This array has the size of 24 * MaxBackends + 16. 24kB for 1000\n> backends. It could be on dsm since this feature is not used\n> commonly.\n\nSorry but I'm not sure this calculation.\nDo you mean 16.24kB for 1000 backends?\n\nRegarding dsm, do you imagine using hoge on dsm?\n\n> \n> - The way to cancel a request already made. (or management of the dump\n> state transition.)\n> \n> Cancellation seems to contain some race conditions. But basically\n> that could be done by sending a request signal after setting the\n> hoge.requestor above to some special value, not needing the third\n\nI imagined hoge.requestor was set to requestor's backendid.\nIsn't it hoge.status?\n\n> type of signal. The special value should be different from the\n> initial state, which signals that the process is accepting a new\n> request.\n> \n> As the whole, that would looks like the folloing?\n> \n> ------------------------------------------------------------\n> Successful request.\n> \n> Requestor dumper state\n> [idle] initial\n> [request] -------------------> requestor pid/backendid\n> -signal->\n> [dumping]\n> <-signal-[done]\n> [read]\n> [done] --------------------> initial\n> \n> ------------------------------------------------------------\n> On failure, the dumper signals with setting state to initial.\n> [request] -------------------> requestor pid/backendid\n> -signal->\n> [dumping]\n> \t\t\t\t\t[failed] initial\n> <-signal-\n> (some other requestor might come meantime.)\n> <sees that the requestor is not me>\n\nIs this \"some other requestor come case\" relevant to the dumper failure?\n\nRegards,\n\n--\nAtsushi Torikoshi\n\n> [failed]\n> \n> ------------------------------------------------------------\n> If the requestor wants to cancel the request, it sets the state to\n> 'cancel' then signal.\n> \n> Requestor dumper state\n> [idle] initial\n> [request] -------------------> cancel\n> <if canceled. clean up>\n> [dumping]\n> <if canceled. clean up>\n> <-signal-[done]\n> \n> -signal-><try to clean up>\n> \n> \n> Other aspects to cnosider?\n> \n> regards.\n\n\n", "msg_date": "Wed, 28 Oct 2020 15:32:15 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "Hi,\r\n\r\nI noticed that this patch fails on the cfbot.\r\nFor this, I changed the status to: 'Waiting on Author'.\r\n\r\nCheers,\r\n//Georgios\n\nThe new status of this patch is: Waiting on Author\n", "msg_date": "Tue, 10 Nov 2020 15:07:13 +0000", "msg_from": "Georgios Kokolatos <gkokolatos@protonmail.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On 2020-10-28 15:32, torikoshia wrote:\n> On 2020-10-23 13:46, Kyotaro Horiguchi wrote:\n\n>> I think we might need to step-back to basic design of this feature\n>> since this patch seems to have unhandled corner cases that are\n>> difficult to find.\n\nI've written out the basic design below and attached\ncorresponding patch.\n\n # Communication flow between the dumper and the requester\n - (1) When REQUESTING memory context dumping, the dumper adds an entry \nto the shared memory. The entry manages the dump state and it is set to \n'REQUESTING'.\n - (2) The dumper sends the signal to the dumper and wait on the latch.\n - (3) The dumper looks into the corresponding shared memory entry and \nchanges its state to 'DUMPING'.\n - (4) When the dumper completes dumping, it changes the state to \n'DONE' and set the latch.\n - (5) The dumper reads the dump file and shows it to the user. \nFinally, the dumper removes the dump file and reset the shared memory \nentry.\n\n # Query cancellation\n - When the requestor cancels dumping, e.g. signaling using ctrl-C, the \nrequestor changes the status of the shared memory entry to 'CANCELING'.\n - The dumper checks the status when it tries to change the state to \n'DONE' at (4), and if the state is 'CANCELING', it removes the dump file \nand reset the shared memory entry.\n\n # Cleanup dump file and the shared memory entry\n - In the normal case, the dumper removes the dump file and resets the \nshared memory entry as described in (5).\n - When something like query cancellation or process termination \nhappens on the dumper after (1) and before (3), in other words, the \nstate is 'REQUESTING', the requestor does the cleanup.\n - When something happens on the dumper or the requestor after (3) and \nbefore (4), in other words, the state is 'DUMPING', the dumper does the \ncleanup. Specifically, if the requestor cancels the query, it just \nchanges the state to 'CANCELING' and the dumper notices it and cleans up \nthings later. OTOH, when the dumper fails to dump, it cleans up the dump \nfile and deletes the entry on the shared memory.\n - When something happens on the requestor after (4), i.e., the state \nis 'DONE', the requestor does the cleanup.\n - In the case of receiving SIGKILL or power failure, all dump files \nare removed in the crash recovery process.\n\n\nAlthough there was a suggestion that shared memory hash\ntable should be changed to more efficient structures,\nI haven't done it in this patch.\nI think it can be treated separately, I'm going to work\non that later.\n\n\nOn 2020-11-11 00:07, Georgios Kokolatos wrote:\n> Hi,\n> \n> I noticed that this patch fails on the cfbot.\n> For this, I changed the status to: 'Waiting on Author'.\n> \n> Cheers,\n> //Georgios\n> \n> The new status of this patch is: Waiting on Author\n\nThanks for your notification and updated the patch.\nChanged the status to: 'Waiting on Author'.\n\nRegards,\n\n--\nAtsushi Torikoshi", "msg_date": "Mon, 16 Nov 2020 19:58:55 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "\n\nOn 2020/11/16 19:58, torikoshia wrote:\n> On 2020-10-28 15:32, torikoshia wrote:\n>> On 2020-10-23 13:46, Kyotaro Horiguchi wrote:\n> \n>>> I think we might need to step-back to basic design of this feature\n>>> since this patch seems to have unhandled corner cases that are\n>>> difficult to find.\n> \n> I've written out the basic design below and attached\n> corresponding patch.\n\nI'm starting to study how this feature behaves. At first, when I executed\nthe following query, the function never returned. ISTM that since\nthe autovacuum launcher cannot respond to the request of memory\ncontexts dump, the function keeps waiting infinity. Is this a bug?\nProbably we should exclude non-backend proceses from the target\nprocesses to dump? Sorry if this was already discussed.\n\n SELECT pg_get_backend_memory_contexts(pid) FROM pg_stat_activity;\n\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 3 Dec 2020 10:10:06 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "Fujii Masao <masao.fujii@oss.nttdata.com> writes:\n> I'm starting to study how this feature behaves. At first, when I executed\n> the following query, the function never returned. ISTM that since\n> the autovacuum launcher cannot respond to the request of memory\n> contexts dump, the function keeps waiting infinity. Is this a bug?\n> Probably we should exclude non-backend proceses from the target\n> processes to dump? Sorry if this was already discussed.\n\n> SELECT pg_get_backend_memory_contexts(pid) FROM pg_stat_activity;\n\nFWIW, I think this patch is fundamentally unsafe. It's got a\nlot of the same problems that I complained about w.r.t. the\nnearby proposal to allow cross-backend stack trace dumping.\nIt does avoid the trap of thinking that it can do work in\na signal handler, but instead it supposes that it can do\nwork involving very high-level objects such as shared hash tables\nin anyplace that might execute CHECK_FOR_INTERRUPTS. That's\nnever going to be safe: the only real expectation the system\nhas is that CHECK_FOR_INTERRUPTS is called at places where our\nstate is sane enough that a transaction abort can clean up.\nTrying to do things like taking LWLocks is going to lead to\ndeadlocks or worse. We need not even get into the hard questions,\nsuch as what happens when one process or the other exits\nunexpectedly.\n\nI also find the idea that this should be the same SQL function\nas pg_get_backend_memory_contexts to be a seriously bad decision.\nThat means that it's not possible to GRANT the right to examine\nonly your own process's memory --- with this proposal, that means\ngranting the right to inspect every other process as well.\n\nBeyond that, the fact that there's no way to restrict the capability\nto just, say, other processes owned by the same user means that\nit's not really safe to GRANT to non-superusers anyway. Even with\nsuch a restriction added, things are problematic, since for example\nit would be possible to inquire into the workings of a\nsecurity-definer function executing in another process that\nnominally is owned by your user.\n\nBetween the security and implementation issues here, I really\nthink we'd be best advised to just reject the concept, period.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 02 Dec 2020 20:36:50 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On 2020-12-03 10:36, Tom Lane wrote:\n> Fujii Masao <masao.fujii@oss.nttdata.com> writes:\n>> I'm starting to study how this feature behaves. At first, when I \n>> executed\n>> the following query, the function never returned. ISTM that since\n>> the autovacuum launcher cannot respond to the request of memory\n>> contexts dump, the function keeps waiting infinity. Is this a bug?\n>> Probably we should exclude non-backend proceses from the target\n>> processes to dump? Sorry if this was already discussed.\n> \n>> SELECT pg_get_backend_memory_contexts(pid) FROM pg_stat_activity;\n\nThanks for trying it!\n\nIt was not discussed explicitly, and I was going to do it later\nas commented.\n\n> +\t\t/* TODO: Check also whether backend or not. */\n\n> \n> FWIW, I think this patch is fundamentally unsafe. It's got a\n> lot of the same problems that I complained about w.r.t. the\n> nearby proposal to allow cross-backend stack trace dumping.\n> It does avoid the trap of thinking that it can do work in\n> a signal handler, but instead it supposes that it can do\n> work involving very high-level objects such as shared hash tables\n> in anyplace that might execute CHECK_FOR_INTERRUPTS. That's\n> never going to be safe: the only real expectation the system\n> has is that CHECK_FOR_INTERRUPTS is called at places where our\n> state is sane enough that a transaction abort can clean up.\n> Trying to do things like taking LWLocks is going to lead to\n> deadlocks or worse. We need not even get into the hard questions,\n> such as what happens when one process or the other exits\n> unexpectedly.\n\nThanks for reviewing!\n\nI may misunderstand something, but the dumper works not at\nCHECK_FOR_INTERRUPTS but during the client read, i.e.,\nProcessClientReadInterrupt().\n\nIs it also unsafe?\n\n\nBTW, since there was a comment that the shared hash table\nused too much memory, I'm now rewriting this patch not to use\nthe shared hash table but a simpler static shared memory struct.\n\n> I also find the idea that this should be the same SQL function\n> as pg_get_backend_memory_contexts to be a seriously bad decision.\n> That means that it's not possible to GRANT the right to examine\n> only your own process's memory --- with this proposal, that means\n> granting the right to inspect every other process as well.\n> \n> Beyond that, the fact that there's no way to restrict the capability\n> to just, say, other processes owned by the same user means that\n> it's not really safe to GRANT to non-superusers anyway. Even with\n> such a restriction added, things are problematic, since for example\n> it would be possible to inquire into the workings of a\n> security-definer function executing in another process that\n> nominally is owned by your user.\n\nI'm going to change the function name and restrict the executor to\nsuperusers. Is it enough?\n\n\nRegards,\n\n\n", "msg_date": "Fri, 04 Dec 2020 19:16:12 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On 2020-12-04 19:16, torikoshia wrote:\n> On 2020-12-03 10:36, Tom Lane wrote:\n>> Fujii Masao <masao.fujii@oss.nttdata.com> writes:\n>>> I'm starting to study how this feature behaves. At first, when I \n>>> executed\n>>> the following query, the function never returned. ISTM that since\n>>> the autovacuum launcher cannot respond to the request of memory\n>>> contexts dump, the function keeps waiting infinity. Is this a bug?\n>>> Probably we should exclude non-backend proceses from the target\n>>> processes to dump? Sorry if this was already discussed.\n>> \n>>> SELECT pg_get_backend_memory_contexts(pid) FROM \n>>> pg_stat_activity;\n> \n> Thanks for trying it!\n> \n> It was not discussed explicitly, and I was going to do it later\n> as commented.\n> \n>> +\t\t/* TODO: Check also whether backend or not. */\n> \n>> \n>> FWIW, I think this patch is fundamentally unsafe. It's got a\n>> lot of the same problems that I complained about w.r.t. the\n>> nearby proposal to allow cross-backend stack trace dumping.\n>> It does avoid the trap of thinking that it can do work in\n>> a signal handler, but instead it supposes that it can do\n>> work involving very high-level objects such as shared hash tables\n>> in anyplace that might execute CHECK_FOR_INTERRUPTS. That's\n>> never going to be safe: the only real expectation the system\n>> has is that CHECK_FOR_INTERRUPTS is called at places where our\n>> state is sane enough that a transaction abort can clean up.\n>> Trying to do things like taking LWLocks is going to lead to\n>> deadlocks or worse. We need not even get into the hard questions,\n>> such as what happens when one process or the other exits\n>> unexpectedly.\n> \n> Thanks for reviewing!\n> \n> I may misunderstand something, but the dumper works not at\n> CHECK_FOR_INTERRUPTS but during the client read, i.e.,\n> ProcessClientReadInterrupt().\n> \n> Is it also unsafe?\n> \n> \n> BTW, since there was a comment that the shared hash table\n> used too much memory, I'm now rewriting this patch not to use\n> the shared hash table but a simpler static shared memory struct.\n\nAttached a rewritten patch.\n\nAccordingly, I also slightly modified the basic design as below.\n\n---\n# Communication flow between the dumper and the requester\n- (1) When requesting memory context dumping, the dumper changes\nthe struct on the shared memory state from 'ACCEPTABLE' to\n'REQUESTING'.\n- (2) The dumper sends the signal to the dumper process and wait on\nthe latch.\n- (3) When the dumper noticed the signal, it changes the state to\n'DUMPING'.\n- (4) When the dumper completes dumping, it changes the state to\n'DONE' and set the latch.\n- (5) The requestor reads the dump file and shows it to the user.\nFinally, the requestor removes the dump file and reset the shared\nmemory state to 'ACCEPTABLE'.\n\n# Query cancellation\n- When the requestor cancels dumping, e.g. signaling using ctrl-C,\nthe requestor changes the state of the shared memory to 'CANCELING'.\n- The dumper checks the state when it tries to change the state to\n'DONE' at (4), and if the state is 'CANCELING', it initializes the\ndump file and reset the shared memory state to 'ACCEPTABLE'.\n\n# Cleanup dump file and the shared memory\n- In the normal case, the dumper removes the dump file and resets\nthe shared memory entry as described in (5).\n- When something like query cancellation or process termination\nhappens on the dumper after (1) and before (3), in other words,\nthe state is 'REQUESTING', the requestor does the cleanup.\n- When something happens on the dumper or the requestor after (3)\nand before (4), in other words, the state is 'DUMPING', the dumper\ndoes the cleanup. Specifically, if the requestor cancels the query,\nit just changes the state to 'CANCELING' and the dumper notices it\nand cleans up things later.\nOTOH, when the dumper fails to dump, it cleans up the dump file and\nreset the shared memory state.\n- When something happens on the requestor after (4), i.e., the state\nis 'DONE', the requestor does the cleanup.\n- In the case of receiving SIGKILL or power failure, all dump files\nare removed in the crash recovery process.\n---\n\n\n> \n>> I also find the idea that this should be the same SQL function\n>> as pg_get_backend_memory_contexts to be a seriously bad decision.\n>> That means that it's not possible to GRANT the right to examine\n>> only your own process's memory --- with this proposal, that means\n>> granting the right to inspect every other process as well.\n>> \n>> Beyond that, the fact that there's no way to restrict the capability\n>> to just, say, other processes owned by the same user means that\n>> it's not really safe to GRANT to non-superusers anyway. Even with\n>> such a restriction added, things are problematic, since for example\n>> it would be possible to inquire into the workings of a\n>> security-definer function executing in another process that\n>> nominally is owned by your user.\n> \n> I'm going to change the function name and restrict the executor to\n> superusers. Is it enough?\n\nIn the attached patch, I changed the function name to\npg_get_target_backend_memory_contexts() for now.\n\n\nRegards,", "msg_date": "Thu, 10 Dec 2020 10:48:00 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "Hi,\n\nOn Thu, Dec 10, 2020 at 10:48 AM torikoshia <torikoshia@oss.nttdata.com> wrote:\n>\n> On 2020-12-04 19:16, torikoshia wrote:\n> > On 2020-12-03 10:36, Tom Lane wrote:\n> >> Fujii Masao <masao.fujii@oss.nttdata.com> writes:\n> >>> I'm starting to study how this feature behaves. At first, when I\n> >>> executed\n> >>> the following query, the function never returned. ISTM that since\n> >>> the autovacuum launcher cannot respond to the request of memory\n> >>> contexts dump, the function keeps waiting infinity. Is this a bug?\n> >>> Probably we should exclude non-backend proceses from the target\n> >>> processes to dump? Sorry if this was already discussed.\n> >>\n> >>> SELECT pg_get_backend_memory_contexts(pid) FROM\n> >>> pg_stat_activity;\n> >\n> > Thanks for trying it!\n> >\n> > It was not discussed explicitly, and I was going to do it later\n> > as commented.\n> >\n> >> + /* TODO: Check also whether backend or not. */\n> >\n> >>\n> >> FWIW, I think this patch is fundamentally unsafe. It's got a\n> >> lot of the same problems that I complained about w.r.t. the\n> >> nearby proposal to allow cross-backend stack trace dumping.\n> >> It does avoid the trap of thinking that it can do work in\n> >> a signal handler, but instead it supposes that it can do\n> >> work involving very high-level objects such as shared hash tables\n> >> in anyplace that might execute CHECK_FOR_INTERRUPTS. That's\n> >> never going to be safe: the only real expectation the system\n> >> has is that CHECK_FOR_INTERRUPTS is called at places where our\n> >> state is sane enough that a transaction abort can clean up.\n> >> Trying to do things like taking LWLocks is going to lead to\n> >> deadlocks or worse. We need not even get into the hard questions,\n> >> such as what happens when one process or the other exits\n> >> unexpectedly.\n> >\n> > Thanks for reviewing!\n> >\n> > I may misunderstand something, but the dumper works not at\n> > CHECK_FOR_INTERRUPTS but during the client read, i.e.,\n> > ProcessClientReadInterrupt().\n> >\n> > Is it also unsafe?\n> >\n> >\n> > BTW, since there was a comment that the shared hash table\n> > used too much memory, I'm now rewriting this patch not to use\n> > the shared hash table but a simpler static shared memory struct.\n>\n> Attached a rewritten patch.\nThanks for updating patch.\n\nBut when I had applyed the patch to the current HEAD and did make, I\ngot an error due to duplicate OIDs.\nYou need to rebase the patch.\n\n> Accordingly, I also slightly modified the basic design as below.\n>\n> ---\n> # Communication flow between the dumper and the requester\n> - (1) When requesting memory context dumping, the dumper changes\n> the struct on the shared memory state from 'ACCEPTABLE' to\n> 'REQUESTING'.\n> - (2) The dumper sends the signal to the dumper process and wait on\n> the latch.\n> - (3) When the dumper noticed the signal, it changes the state to\n> 'DUMPING'.\n> - (4) When the dumper completes dumping, it changes the state to\n> 'DONE' and set the latch.\n> - (5) The requestor reads the dump file and shows it to the user.\n> Finally, the requestor removes the dump file and reset the shared\n> memory state to 'ACCEPTABLE'.\n>\n> # Query cancellation\n> - When the requestor cancels dumping, e.g. signaling using ctrl-C,\n> the requestor changes the state of the shared memory to 'CANCELING'.\n> - The dumper checks the state when it tries to change the state to\n> 'DONE' at (4), and if the state is 'CANCELING', it initializes the\n> dump file and reset the shared memory state to 'ACCEPTABLE'.\n>\n> # Cleanup dump file and the shared memory\n> - In the normal case, the dumper removes the dump file and resets\n> the shared memory entry as described in (5).\n> - When something like query cancellation or process termination\n> happens on the dumper after (1) and before (3), in other words,\n> the state is 'REQUESTING', the requestor does the cleanup.\n> - When something happens on the dumper or the requestor after (3)\n> and before (4), in other words, the state is 'DUMPING', the dumper\n> does the cleanup. Specifically, if the requestor cancels the query,\n> it just changes the state to 'CANCELING' and the dumper notices it\n> and cleans up things later.\n> OTOH, when the dumper fails to dump, it cleans up the dump file and\n> reset the shared memory state.\n> - When something happens on the requestor after (4), i.e., the state\n> is 'DONE', the requestor does the cleanup.\n> - In the case of receiving SIGKILL or power failure, all dump files\n> are removed in the crash recovery process.\n> ---\nIf the dumper is terminated before it dumps, the requestor will appear\nto enter an\ninfinite loop because the status of mcxtdumpShmem will not change.\nThe following are the steps to reproduce.\n\n - session1\n BEGIN; LOCK TABLE t;\n - session2\n SELECT * FROM t; -- wait\n - session3\n select pg_get_target_backend_memory_contexts(<pid of session2>); -- wait\n - session1\n select pg_terminate_backend(<pid of session2>); -- kill session2\n - session3 waits forever.\n\nTherefore, you may need to set mcxtdumpShmem->dump_status to\nMCXTDUMPSTATUS_CANCELING\nor other status before the dumper terminates.\n\nAlso, although I have not been able to reproduce it, I believe that\nwith the current design,\nif the requestor disappears right after the dumper dumps the memory information,\nthe dump file will remain.\nSince the current design appears to allow only one requestor per\ninstance, when the requestor\nrequests a dump, it might be a good idea to delete any remaining dump\nfiles, if any.\n\nThe following are comments on the code.\n\n+ proc = BackendPidGetProc(dst_pid);\n+\n+ if (proc == NULL)\n+ {\n+ ereport(WARNING,\n+ (errmsg(\"PID %d is not a PostgreSQL server process\", dst_pid)));\n+\n+ return (Datum) 1;\n+ }\nFor now, background writer, checkpointer and WAL writer are belong to\nthe auxiliary process.\nTherefore, if we specify the PIDs of these processes for\npg_get_target_backend_memory_contexts(),\n\"PID xxxx is not a PostgreSQL server process\" whould be outoput.\nThis confuses the user.\nHow about use AuxiliaryPidGetProc() to determine these processes?\n\n+ ereport(INFO,\n+ (errmsg(\"The request has failed and now PID %d is\nrequsting dumping.\",\n+ mcxtdumpShmem->src_pid)));\n+\n+ LWLockRelease(McxtDumpLock);\nYou can release LWLock before ereport.\n\n+ Assert(mcxtdumpShmem->dump_status = MCXTDUMPSTATUS_REQUESTING);\ntypo?\nIt might be \"mcxtdumpShmem->dump_status == MCXTDUMPSTATUS_REQUESTING\".\n\n+ ereport(INFO,\n+ (errmsg(\"PID %d is looked up by another process\", pid)));\nThis message is not accurate.\nBecause, in the current design, only one session can request a dump,\nso if there are multiple requests, this message will be output even if the\nrequest is for a PID that is not looked up.\n\n+ if (fpout == NULL)\n+ {\n+ ereport(LOG,\n+ (errcode_for_file_access(),\n+ errmsg(\"could not write memory context file \\\"%s\\\": %m\",\n+ dumpfile)));\nIt would be better to use \"dump file\" instead of \"memory context file\".\n\n+static void\n+McxtReqKill(int code, Datum arg)\nThe function McxtReqKill looks like it should have a different name.\n(Since it doesn't do any kill).\nHow about McxtReqcCleanup or something similar?\n\nBest regards,\n\n> >> I also find the idea that this should be the same SQL function\n> >> as pg_get_backend_memory_contexts to be a seriously bad decision.\n> >> That means that it's not possible to GRANT the right to examine\n> >> only your own process's memory --- with this proposal, that means\n> >> granting the right to inspect every other process as well.\n> >>\n> >> Beyond that, the fact that there's no way to restrict the capability\n> >> to just, say, other processes owned by the same user means that\n> >> it's not really safe to GRANT to non-superusers anyway. Even with\n> >> such a restriction added, things are problematic, since for example\n> >> it would be possible to inquire into the workings of a\n> >> security-definer function executing in another process that\n> >> nominally is owned by your user.\n> >\n> > I'm going to change the function name and restrict the executor to\n> > superusers. Is it enough?\n>\n> In the attached patch, I changed the function name to\n> pg_get_target_backend_memory_contexts() for now.\n>\n>\n> Regards,\n\n\n\n-- \nTatsuhito Kasahara\nkasahara.tatsuhito _at_ gmail.com\n\n\n", "msg_date": "Fri, 25 Dec 2020 18:08:17 +0900", "msg_from": "Kasahara Tatsuhito <kasahara.tatsuhito@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On Fri, Dec 25, 2020 at 6:08 PM Kasahara Tatsuhito \n<kasahara.tatsuhito@gmail.com> wrote:\n\nThanks for reviewing and kind suggestion!\n\n>> Attached a rewritten patch.\n> Thanks for updating patch.\n> \n> But when I had applyed the patch to the current HEAD and did make, I\n> got an error due to duplicate OIDs.\n> You need to rebase the patch.\n\nAssigned another OID.\n\n>> Accordingly, I also slightly modified the basic design as below.\n>> \n>> ---\n>> # Communication flow between the dumper and the requester\n>> - (1) When requesting memory context dumping, the dumper changes\n>> the struct on the shared memory state from 'ACCEPTABLE' to\n>> 'REQUESTING'.\n>> - (2) The dumper sends the signal to the dumper process and wait on\n>> the latch.\n>> - (3) When the dumper noticed the signal, it changes the state to\n>> 'DUMPING'.\n>> - (4) When the dumper completes dumping, it changes the state to\n>> 'DONE' and set the latch.\n>> - (5) The requestor reads the dump file and shows it to the user.\n>> Finally, the requestor removes the dump file and reset the shared\n>> memory state to 'ACCEPTABLE'.\n>> \n>> # Query cancellation\n>> - When the requestor cancels dumping, e.g. signaling using ctrl-C,\n>> the requestor changes the state of the shared memory to 'CANCELING'.\n>> - The dumper checks the state when it tries to change the state to\n>> 'DONE' at (4), and if the state is 'CANCELING', it initializes the\n>> dump file and reset the shared memory state to 'ACCEPTABLE'.\n>> \n>> # Cleanup dump file and the shared memory\n>> - In the normal case, the dumper removes the dump file and resets\n>> the shared memory entry as described in (5).\n>> - When something like query cancellation or process termination\n>> happens on the dumper after (1) and before (3), in other words,\n>> the state is 'REQUESTING', the requestor does the cleanup.\n>> - When something happens on the dumper or the requestor after (3)\n>> and before (4), in other words, the state is 'DUMPING', the dumper\n>> does the cleanup. Specifically, if the requestor cancels the query,\n>> it just changes the state to 'CANCELING' and the dumper notices it\n>> and cleans up things later.\n>> OTOH, when the dumper fails to dump, it cleans up the dump file and\n>> reset the shared memory state.\n>> - When something happens on the requestor after (4), i.e., the state\n>> is 'DONE', the requestor does the cleanup.\n>> - In the case of receiving SIGKILL or power failure, all dump files\n>> are removed in the crash recovery process.\n>> ---\n> If the dumper is terminated before it dumps, the requestor will appear\n> to enter an\n> infinite loop because the status of mcxtdumpShmem will not change.\n> The following are the steps to reproduce.\n> \n>  - session1\n>    BEGIN; LOCK TABLE t;\n>    - session2\n>      SELECT * FROM t; -- wait\n>      - session3\n>        select pg_get_target_backend_memory_contexts(<pid of session2>); \n> -- wait\n>  - session1\n>    select pg_terminate_backend(<pid of session2>); -- kill session2\n>      - session3 waits forever.\n> \n> Therefore, you may need to set mcxtdumpShmem->dump_status to\n> MCXTDUMPSTATUS_CANCELING\n> or other status before the dumper terminates.\n\nIn this case, it may be difficult for the dumper to change dump_status \nbecause\nit's waiting for latch and dump_memory_contexts() is not called yet.\n\nInstead, it's possible for the requestor to check the existence of the \ndumper\nprocess periodically during waiting.\nI added this logic to the attached patch.\n\n\n> Also, although I have not been able to reproduce it, I believe that\n> with the current design,\n> if the requestor disappears right after the dumper dumps the memory \n> information,\n> the dump file will remain.\n> Since the current design appears to allow only one requestor per\n> instance, when the requestor\n> requests a dump, it might be a good idea to delete any remaining dump\n> files, if any.\n\nAlthough I'm not sure when the dump file remains, deleting any remaining \ndump\nfiles seems good for safety.\nI also added this idea to the attached patch.\n\n\n> The following are comments on the code.\n> \n> +   proc = BackendPidGetProc(dst_pid);\n> +\n> +   if (proc == NULL)\n> +   {\n> +       ereport(WARNING,\n> +               (errmsg(\"PID %d is not a PostgreSQL server process\", \n> dst_pid)));\n> +\n> +       return (Datum) 1;\n> +   }\n> For now, background writer, checkpointer and WAL writer are belong to\n> the auxiliary process.\n> Therefore, if we specify the PIDs of these processes for\n> pg_get_target_backend_memory_contexts(),\n> \"PID xxxx is not a PostgreSQL server process\" whould be outoput.\n> This confuses the user.\n> How about use AuxiliaryPidGetProc() to determine these processes?\n\nThanks and I modified the patch to output the below message when it's an\nauxiliary process.\n\n| PID %d is not a PostgreSQL backend process but an auxiliary process.\n\n> \n> +               ereport(INFO,\n> +                   (errmsg(\"The request has failed and now PID %d is\n> requsting dumping.\",\n> +                       mcxtdumpShmem->src_pid)));\n> +\n> +               LWLockRelease(McxtDumpLock);\n> You can release LWLock before ereport.\n\nModified to release the lock before ereport.\n\n> +   Assert(mcxtdumpShmem->dump_status = MCXTDUMPSTATUS_REQUESTING);\n> typo?\n> It might be \"mcxtdumpShmem->dump_status == MCXTDUMPSTATUS_REQUESTING\".\n\nOps, it's a serious typo. Fixed it.\n\n> +           ereport(INFO,\n> +                   (errmsg(\"PID %d is looked up by another process\", \n> pid)));\n> This message is not accurate.\n> Because, in the current design, only one session can request a dump,\n> so if there are multiple requests, this message will be output even if \n> the\n> request is for a PID that is not looked up.\n\nExactly. Modified the message as below.\n\n| Only one session can dump at a time and another session is dumping \ncurrently.\n\n> +   if (fpout == NULL)\n> +   {\n> +       ereport(LOG,\n> +               (errcode_for_file_access(),\n> +                errmsg(\"could not write memory context file \\\"%s\\\": \n> %m\",\n> +                       dumpfile)));\n> It would be better to use \"dump file\" instead of \"memory context file\".\n> \n> +static void\n> +McxtReqKill(int code, Datum arg)\n> The function McxtReqKill looks like it should have a different name.\n> (Since it doesn't do any kill).\n> How about McxtReqcCleanup or something similar?\n\nThanks for your idea and I changed the name to McxtReqCleanup.\n\n\nRegards,", "msg_date": "Mon, 04 Jan 2021 14:34:50 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "v7 that fixes recent conflicts.\n\nIt also changed the behavior of requestor when another requestor is\nalready working for simplicity.\nIn this case, v6 patch makes the requestor wait. v7 patch makes the\nrequestor quit.\n\n\nRegards,\n\n--\nAtsushi Torikoshi", "msg_date": "Tue, 12 Jan 2021 21:21:18 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "Since pg_get_target_backend_memory_contexts() waits to dump memory and\nit could lead dead lock as below.\n\n - session1\n BEGIN; TRUNCATE t;\n\n - session2\n BEGIN; TRUNCATE t; -- wait\n\n - session1\n SELECT * FROM pg_get_target_backend_memory_contexts(<pid of session \n2>); --wait\n\n\nThanks for notifying me, Fujii-san.\n\n\nAttached v8 patch that prohibited calling the function inside \ntransactions.\n\n\nRegards,\n\n--\nAtsushi Torikoshi", "msg_date": "Thu, 14 Jan 2021 19:11:23 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On 2021-01-14 19:11, torikoshia wrote:\n> Since pg_get_target_backend_memory_contexts() waits to dump memory and\n> it could lead dead lock as below.\n> \n> - session1\n> BEGIN; TRUNCATE t;\n> \n> - session2\n> BEGIN; TRUNCATE t; -- wait\n> \n> - session1\n> SELECT * FROM pg_get_target_backend_memory_contexts(<pid of session\n> 2>); --wait\n> \n> \n> Thanks for notifying me, Fujii-san.\n> \n> \n> Attached v8 patch that prohibited calling the function inside \n> transactions.\n\nRegrettably, this modification could not cope with the advisory lock and\nI haven't come up with a good way to deal with it.\n\nIt seems to me that the architecture of the requestor waiting for the\ndumper leads to this problem and complicates things.\n\n\nConsidering the discussion printing backtrace discussion[1], it seems\nreasonable that the requestor just sends a signal and dumper dumps to\nthe log file.\n\nSince I found a past discussion that was doing exactly what I thought\nreasonable[2], I'm going to continue that discussion if there are no\nobjections.\n\n\nAny thought?\n\n\n[1] \nhttps://www.postgresql.org/message-id/flat/CALDaNm3ZzmFS-=r7oDUzj7y7BgQv+N06Kqyft6C3xZDoKnk_6w@mail.gmail.com\n[2] \nhttps://www.postgresql.org/message-id/flat/20171212044330.3nclev2sfrab36tf%40alap3.anarazel.de#6f28be9839c74779ed6aaa75616124f5\n\n\nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 04 Mar 2021 18:32:33 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "\n\nOn 2021/03/04 18:32, torikoshia wrote:\n> On 2021-01-14 19:11, torikoshia wrote:\n>> Since pg_get_target_backend_memory_contexts() waits to dump memory and\n>> it could lead dead lock as below.\n>>\n>>   - session1\n>>   BEGIN; TRUNCATE t;\n>>\n>>   - session2\n>>   BEGIN; TRUNCATE t; -- wait\n>>\n>>   - session1\n>>   SELECT * FROM pg_get_target_backend_memory_contexts(<pid of session\n>> 2>); --wait\n>>\n>>\n>> Thanks for notifying me, Fujii-san.\n>>\n>>\n>> Attached v8 patch that prohibited calling the function inside transactions.\n> \n> Regrettably, this modification could not cope with the advisory lock and\n> I haven't come up with a good way to deal with it.\n> \n> It seems to me that the architecture of the requestor waiting for the\n> dumper leads to this problem and complicates things.\n> \n> \n> Considering the discussion printing backtrace discussion[1], it seems\n> reasonable that the requestor just sends a signal and dumper dumps to\n> the log file.\n\n+1\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Fri, 5 Mar 2021 14:22:56 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On 2021-03-05 14:22, Fujii Masao wrote:\n> On 2021/03/04 18:32, torikoshia wrote:\n>> On 2021-01-14 19:11, torikoshia wrote:\n>>> Since pg_get_target_backend_memory_contexts() waits to dump memory \n>>> and\n>>> it could lead dead lock as below.\n>>> \n>>>   - session1\n>>>   BEGIN; TRUNCATE t;\n>>> \n>>>   - session2\n>>>   BEGIN; TRUNCATE t; -- wait\n>>> \n>>>   - session1\n>>>   SELECT * FROM pg_get_target_backend_memory_contexts(<pid of session\n>>> 2>); --wait\n>>> \n>>> \n>>> Thanks for notifying me, Fujii-san.\n>>> \n>>> \n>>> Attached v8 patch that prohibited calling the function inside \n>>> transactions.\n>> \n>> Regrettably, this modification could not cope with the advisory lock \n>> and\n>> I haven't come up with a good way to deal with it.\n>> \n>> It seems to me that the architecture of the requestor waiting for the\n>> dumper leads to this problem and complicates things.\n>> \n>> \n>> Considering the discussion printing backtrace discussion[1], it seems\n>> reasonable that the requestor just sends a signal and dumper dumps to\n>> the log file.\n> \n> +1\n\nThanks!\n\nI remade the patch and introduced a function\npg_print_backend_memory_contexts(PID) which prints the memory contexts \nof\nthe specified PID to elog.\n\n =# SELECT pg_print_backend_memory_contexts(450855);\n\n ** log output **\n 2021-03-17 15:21:01.942 JST [450855] LOG: Printing memory contexts of \nPID 450855\n 2021-03-17 15:21:01.942 JST [450855] LOG: level: 0 TopMemoryContext: \n68720 total in 5 blocks; 16312 free (15 chunks); 52408 used\n 2021-03-17 15:21:01.942 JST [450855] LOG: level: 1 Prepared Queries: \n65536 total in 4 blocks; 35088 free (14 chunks); 30448 used\n 2021-03-17 15:21:01.942 JST [450855] LOG: level: 1 pgstat \nTabStatusArray lookup hash table: 8192 total in 1 blocks; 1408 free (0 \nchunks); 6784 used\n ..(snip)..\n 2021-03-17 15:21:01.942 JST [450855] LOG: level: 2 CachedPlanSource: \n4096 total in 3 blocks; 680 free (0 chunks); 3416 used: PREPARE hoge_200 \nAS SELECT * FROM pgbench_accounts WHERE aid = \n1111111111111111111111111111111111111...\n 2021-03-17 15:21:01.942 JST [450855] LOG: level: 3 CachedPlanQuery: \n4096 total in 3 blocks; 464 free (0 chunks); 3632 used\n ..(snip)..\n 2021-03-17 15:21:01.945 JST [450855] LOG: level: 1 Timezones: 104128 \ntotal in 2 blocks; 2584 free (0 chunks); 101544 used\n 2021-03-17 15:21:01.945 JST [450855] LOG: level: 1 ErrorContext: 8192 \ntotal in 1 blocks; 7928 free (5 chunks); 264 used\n 2021-03-17 15:21:01.945 JST [450855] LOG: Grand total: 2802080 bytes \nin 1399 blocks; 480568 free (178 chunks); 2321512 used\n\n\nAs above, the output is almost the same as MemoryContextStatsPrint()\nexcept for the way of expression of the level.\nMemoryContextStatsPrint() uses indents, but\npg_print_backend_memory_contexts() writes it as \"level: %d\".\n\nSince there was discussion about enlarging StringInfo may cause\nerrors on OOM[1], this patch calls elog for each context.\n\nAs with MemoryContextStatsPrint(), each context shows 100\nchildren at most.\nI once thought it should be configurable, but something like\npg_print_backend_memory_contexts(PID, num_children) needs to send\nthe 'num_children' from requestor to dumper and it seems to require\nanother infrastructure.\nCreating a new GUC for this seems overkill.\nIf MemoryContextStatsPrint(), i.e. showing 100 children at most is\nenough, this hard limit may be acceptable.\n\nOnly superusers can call pg_print_backend_memory_contexts().\n\nI'm going to add documentation and regression tests.\n\n\nAny thoughts?\n\n\n[1] \nhttps://www.postgresql.org/message-id/CAMsr%2BYGh%2Bsso5N6Q%2BFmYHLWC%3DBPCzA%2B5GbhYZSGruj2d0c7Vvg%40mail.gmail.com\n\"r_d/strengthen_perf/print_memcon.md\" 110L, 5642C written\n\n\nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA CORPORATION", "msg_date": "Wed, 17 Mar 2021 22:24:27 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "\n\nOn 2021/03/17 22:24, torikoshia wrote:\n> I remade the patch and introduced a function\n> pg_print_backend_memory_contexts(PID) which prints the memory contexts of\n> the specified PID to elog.\n\nThanks for the patch!\n\n\n>   =# SELECT pg_print_backend_memory_contexts(450855);\n> \n>   ** log output **\n>   2021-03-17 15:21:01.942 JST [450855] LOG:  Printing memory contexts of PID 450855\n>   2021-03-17 15:21:01.942 JST [450855] LOG:  level: 0 TopMemoryContext: 68720 total in 5 blocks; 16312 free (15 chunks); 52408 used\n>   2021-03-17 15:21:01.942 JST [450855] LOG:  level: 1 Prepared Queries: 65536 total in 4 blocks; 35088 free (14 chunks); 30448 used\n>   2021-03-17 15:21:01.942 JST [450855] LOG:  level: 1 pgstat TabStatusArray lookup hash table: 8192 total in 1 blocks; 1408 free (0 chunks); 6784 used\n>   ..(snip)..\n>   2021-03-17 15:21:01.942 JST [450855] LOG:  level: 2 CachedPlanSource: 4096 total in 3 blocks; 680 free (0 chunks); 3416 used: PREPARE hoge_200 AS SELECT * FROM pgbench_accounts WHERE aid = 1111111111111111111111111111111111111...\n>   2021-03-17 15:21:01.942 JST [450855] LOG:  level: 3 CachedPlanQuery: 4096 total in 3 blocks; 464 free (0 chunks); 3632 used\n>   ..(snip)..\n>   2021-03-17 15:21:01.945 JST [450855] LOG:  level: 1 Timezones: 104128 total in 2 blocks; 2584 free (0 chunks); 101544 used\n>   2021-03-17 15:21:01.945 JST [450855] LOG:  level: 1 ErrorContext: 8192 total in 1 blocks; 7928 free (5 chunks); 264 used\n>   2021-03-17 15:21:01.945 JST [450855] LOG:  Grand total: 2802080 bytes in 1399 blocks; 480568 free (178 chunks); 2321512 used\n> \n> \n> As above, the output is almost the same as MemoryContextStatsPrint()\n> except for the way of expression of the level.\n> MemoryContextStatsPrint() uses indents, but\n> pg_print_backend_memory_contexts() writes it as \"level: %d\".\n\nThis format looks better to me.\n\n\n> Since there was discussion about enlarging StringInfo may cause\n> errors on OOM[1], this patch calls elog for each context.\n> \n> As with MemoryContextStatsPrint(), each context shows 100\n> children at most.\n> I once thought it should be configurable, but something like\n> pg_print_backend_memory_contexts(PID, num_children) needs to send\n> the 'num_children' from requestor to dumper and it seems to require\n> another infrastructure.\n> Creating a new GUC for this seems overkill.\n> If MemoryContextStatsPrint(), i.e. showing 100 children at most is\n> enough, this hard limit may be acceptable.\n\nCan't this number be passed via shared memory?\n\n\n> Only superusers can call pg_print_backend_memory_contexts().\n\n+\t/* Only allow superusers to signal superuser-owned backends. */\n+\tif (superuser_arg(proc->roleId) && !superuser())\n\nThe patch seems to allow even non-superuser to request to print the memory\ncontexts if the target backend is owned by non-superuser. Is this intentional?\nI think that only superuser should be allowed to execute\npg_print_backend_memory_contexts() whoever owns the target backend.\nBecause that function can cause lots of log messages.\n\n\n> I'm going to add documentation and regression tests.\n\nThanks!\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 18 Mar 2021 15:09:28 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On 2021-03-18 15:09, Fujii Masao wrote:\n\nThanks for your comments!\n\n> On 2021/03/17 22:24, torikoshia wrote:\n>> I remade the patch and introduced a function\n>> pg_print_backend_memory_contexts(PID) which prints the memory contexts \n>> of\n>> the specified PID to elog.\n> \n> Thanks for the patch!\n> \n> \n>>   =# SELECT pg_print_backend_memory_contexts(450855);\n>> \n>>   ** log output **\n>>   2021-03-17 15:21:01.942 JST [450855] LOG:  Printing memory contexts \n>> of PID 450855\n>>   2021-03-17 15:21:01.942 JST [450855] LOG:  level: 0 \n>> TopMemoryContext: 68720 total in 5 blocks; 16312 free (15 chunks); \n>> 52408 used\n>>   2021-03-17 15:21:01.942 JST [450855] LOG:  level: 1 Prepared \n>> Queries: 65536 total in 4 blocks; 35088 free (14 chunks); 30448 used\n>>   2021-03-17 15:21:01.942 JST [450855] LOG:  level: 1 pgstat \n>> TabStatusArray lookup hash table: 8192 total in 1 blocks; 1408 free (0 \n>> chunks); 6784 used\n>>   ..(snip)..\n>>   2021-03-17 15:21:01.942 JST [450855] LOG:  level: 2 \n>> CachedPlanSource: 4096 total in 3 blocks; 680 free (0 chunks); 3416 \n>> used: PREPARE hoge_200 AS SELECT * FROM pgbench_accounts WHERE aid = \n>> 1111111111111111111111111111111111111...\n>>   2021-03-17 15:21:01.942 JST [450855] LOG:  level: 3 \n>> CachedPlanQuery: 4096 total in 3 blocks; 464 free (0 chunks); 3632 \n>> used\n>>   ..(snip)..\n>>   2021-03-17 15:21:01.945 JST [450855] LOG:  level: 1 Timezones: \n>> 104128 total in 2 blocks; 2584 free (0 chunks); 101544 used\n>>   2021-03-17 15:21:01.945 JST [450855] LOG:  level: 1 ErrorContext: \n>> 8192 total in 1 blocks; 7928 free (5 chunks); 264 used\n>>   2021-03-17 15:21:01.945 JST [450855] LOG:  Grand total: 2802080 \n>> bytes in 1399 blocks; 480568 free (178 chunks); 2321512 used\n>> \n>> \n>> As above, the output is almost the same as MemoryContextStatsPrint()\n>> except for the way of expression of the level.\n>> MemoryContextStatsPrint() uses indents, but\n>> pg_print_backend_memory_contexts() writes it as \"level: %d\".\n> \n> This format looks better to me.\n> \n> \n>> Since there was discussion about enlarging StringInfo may cause\n>> errors on OOM[1], this patch calls elog for each context.\n>> \n>> As with MemoryContextStatsPrint(), each context shows 100\n>> children at most.\n>> I once thought it should be configurable, but something like\n>> pg_print_backend_memory_contexts(PID, num_children) needs to send\n>> the 'num_children' from requestor to dumper and it seems to require\n>> another infrastructure.\n>> Creating a new GUC for this seems overkill.\n>> If MemoryContextStatsPrint(), i.e. showing 100 children at most is\n>> enough, this hard limit may be acceptable.\n> \n> Can't this number be passed via shared memory?\n\nThe attached patch uses static shared memory to pass the number.\n\nAs documented, the current implementation allows that when multiple\npg_print_backend_memory_contexts() called in succession or\nsimultaneously, max_children can be the one of another\npg_print_backend_memory_contexts().\n\nI had tried to avoid this by adding some state information and using\nbefore_shmem_exit() in case of process termination for cleaning up the\nstate information as in the patch I presented earlier, but since kill()\nreturns success before the dumper called signal handler, it seemed\nthere were times when we couldn't clean up the state.\n\nSince this happens only when multiple pg_print_backend_memory_contexts()\nare called and their specified number of children are different, and the\neffect is just the not intended number of children to print, it might be\nacceptable.\n\nOr it might be better to wait for some seconds if num_chilren on shared\nmemory is not the initialized value(meaning some other process is\nrequesting to print memory contexts).\n\n>> Only superusers can call pg_print_backend_memory_contexts().\n> \n> +\t/* Only allow superusers to signal superuser-owned backends. */\n> +\tif (superuser_arg(proc->roleId) && !superuser())\n> \n> The patch seems to allow even non-superuser to request to print the \n> memory\n> contexts if the target backend is owned by non-superuser. Is this \n> intentional?\n> I think that only superuser should be allowed to execute\n> pg_print_backend_memory_contexts() whoever owns the target backend.\n> Because that function can cause lots of log messages.\n\nThanks, it's not intentional, modified it.\n\n>> I'm going to add documentation and regression tests.\n\nAdded them.\n\nRegards,", "msg_date": "Mon, 22 Mar 2021 15:09:58 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "At Mon, 22 Mar 2021 15:09:58 +0900, torikoshia <torikoshia@oss.nttdata.com> wrote in \n> >> If MemoryContextStatsPrint(), i.e. showing 100 children at most is\n> >> enough, this hard limit may be acceptable.\n> > Can't this number be passed via shared memory?\n> \n> The attached patch uses static shared memory to pass the number.\n\n\"pg_print_backend_memory_contexts\"\n\nThat name looks like as if it returns the result as text when used on\ncommand-line. We could have pg_get_backend_memory_context(bool\ndump_to_log (or where to dump), int limit). Or couldn't we name it\ndifferently even in the ase we add a separate function?\n\n\n+/*\n+ * MaxChildrenPerContext\n+ * \t\tMax number of children to print per one parent context.\n+ */\n+int \t*MaxChildrenPerContext = NULL;\n\nPerhaps it'd be better to have a struct even if it consists only of\none member. (Aligned) C-int values are atomic so we can omit the\nMcxtPrintLock. (I don't think it's a problem even if it is modifed\nwhile reading^^:)\n\n\n+\tif(max_children <= 0)\n+\t{\n+\t\tereport(WARNING,\n+\t\t\t\t(errmsg(\"%d is invalid value\", max_children),\n+\t\t\t\t errhint(\"second parameter is the number of context and it must be set to a value greater than or equal to 1\")));\n\nIt's annoying to choose a number large enough when I want to dump\nchildren unlimitedly. Couldn't we use 0 to specify \"unlimited\"?\n\n+\t\t\t\t(errmsg(\"%d is invalid value\", max_children),\n+\t\t\t\t errhint(\"second parameter is the number of context and it must be set to a value greater than or equal to 1\")));\n\nFor the main message, (I think) we usually spell the \"%d is invalid\nvalue\" as \"maximum number of children must be positive\" or such. For\nthe hint, we don't need a copy of the primary section of the\ndocumentation here.\n\nI think we should ERROR out for invalid parameters, at least for\nmax_children. I'm not sure about pid since we might call it based on\npg_stat_activity..\n\n\n+\tif(!SendProcSignal(pid, PROCSIG_PRINT_MEMORY_CONTEXT, InvalidBackendId))\n\nWe know the backendid of the process here.\n\n\n+\t\t\tif (is_dst_stderr)\n+\t\t\t{\n+\t\t\t\tfor (i = 0; i <= level; i++)\n+\t\t\t\t\tfprintf(stderr, \" \");\n\nThe fprintf path is used nowhere in the patch at all. It can be used\nwhile attaching debugger but I'm not sure we need that code. The\nfootprint of this patch is largely shrinked by removing it.\n\n\n+\t\tstrcat(truncated_ident, delimiter);\n\nstrcpy is sufficient here. And we don't need the delimiter to be a\nvariable. (we can copy a string literal into truncate_ident, then\ncount the length of truncate_ident, instead of the delimiter\nvariable.)\n\n\n+\t\t$current_logfiles = slurp_file($node->data_dir . '/current_logfiles');\n...\n+my $lfname = $current_logfiles;\n+$lfname =~ s/^stderr //;\n+chomp $lfname;\n\n$node->logfile is the current log file name.\n\n+\t'target PID is not PostgreSQL server process');\n\nMaybe \"check if PID check is working\" or such? And, we can do\nsomething like the following to exercise in a more practical way.\n\n select pg_print_backend...(pid,) from pg_stat_activity where backend_type = 'checkpointer';\n\n> As documented, the current implementation allows that when multiple\n> pg_print_backend_memory_contexts() called in succession or\n> simultaneously, max_children can be the one of another\n> pg_print_backend_memory_contexts().\n> I had tried to avoid this by adding some state information and using\n> before_shmem_exit() in case of process termination for cleaning up the\n> state information as in the patch I presented earlier, but since\n> kill()\n> returns success before the dumper called signal handler, it seemed\n> there were times when we couldn't clean up the state.\n> Since this happens only when multiple\n> pg_print_backend_memory_contexts()\n> are called and their specified number of children are different, and\n> the\n> effect is just the not intended number of children to print, it might\n> be\n> acceptable.\n\nI see it as a non-issue. Even though the behavior looks somewhat\nstrange, that usage is stranger than the behavior.\n\n> Or it might be better to wait for some seconds if num_chilren on\n> shared\n> memory is not the initialized value(meaning some other process is\n> requesting to print memory contexts).\n> \n> >> Only superusers can call pg_print_backend_memory_contexts().\n> > +\t/* Only allow superusers to signal superuser-owned backends. */\n> > +\tif (superuser_arg(proc->roleId) && !superuser())\n> > The patch seems to allow even non-superuser to request to print the\n> > memory\n> > contexts if the target backend is owned by non-superuser. Is this\n> > intentional?\n> > I think that only superuser should be allowed to execute\n> > pg_print_backend_memory_contexts() whoever owns the target backend.\n> > Because that function can cause lots of log messages.\n> \n> Thanks, it's not intentional, modified it.\n\nBy the way we can send a procsig to other than a client backend. And\nmost of the postgres processes are using the standard signal handler\nand intializes the procsig facility. So some of such kind of processes\ncan dump the memory context information as-is. Otherwise we can add\nCHECK_FOR_INTERRUPT to appropriate place to allow that. I'm not sure\nhow it is useful for other kind of processes, but it might be useful\nfor autovacuum workers.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Tue, 23 Mar 2021 17:24:33 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On 2021-03-23 17:24, Kyotaro Horiguchi wrote:\n\nThanks for reviewing and suggestions!\n\n> At Mon, 22 Mar 2021 15:09:58 +0900, torikoshia\n> <torikoshia@oss.nttdata.com> wrote in\n>> >> If MemoryContextStatsPrint(), i.e. showing 100 children at most is\n>> >> enough, this hard limit may be acceptable.\n>> > Can't this number be passed via shared memory?\n>> \n>> The attached patch uses static shared memory to pass the number.\n> \n> \"pg_print_backend_memory_contexts\"\n> \n> That name looks like as if it returns the result as text when used on\n> command-line. We could have pg_get_backend_memory_context(bool\n> dump_to_log (or where to dump), int limit). Or couldn't we name it\n> differently even in the ase we add a separate function?\n\nRedefined pg_get_backend_memory_contexts() as\npg_get_backend_memory_contexts(pid, int max_children).\n\nWhen pid equals 0, pg_get_backend_memory_contexts() prints local memory\ncontexts as original pg_get_backend_memory_contexts() does.\nIn this case, 'max_children' is ignored.\n\nWhen 'pid' does not equal 0 and it is the PID of the client backend,\n memory contexts are logged through elog().\n\n> \n> +/*\n> + * MaxChildrenPerContext\n> + * Max number of children to print per one parent context.\n> + */\n> +int *MaxChildrenPerContext = NULL;\n> \n> Perhaps it'd be better to have a struct even if it consists only of\n> one member. (Aligned) C-int values are atomic so we can omit the\n> McxtPrintLock. (I don't think it's a problem even if it is modifed\n> while reading^^:)\n\nFixed them.\n\n> + if(max_children <= 0)\n> + {\n> + ereport(WARNING,\n> + (errmsg(\"%d is invalid value\", \n> max_children),\n> + errhint(\"second parameter is the number \n> of context and it must\n> be set to a value greater than or equal to 1\")));\n> \n> It's annoying to choose a number large enough when I want to dump\n> children unlimitedly. Couldn't we use 0 to specify \"unlimited\"?\n\nModified as you suggested.\n\n> + (errmsg(\"%d is invalid value\", \n> max_children),\n> + errhint(\"second parameter is the number \n> of context and it must\n> be set to a value greater than or equal to 1\")));\n> \n> For the main message, (I think) we usually spell the \"%d is invalid\n> value\" as \"maximum number of children must be positive\" or such. For\n> the hint, we don't need a copy of the primary section of the\n> documentation here.\n\nModified it to \"The maximum number of children must be greater than 0\".\n\n> \n> I think we should ERROR out for invalid parameters, at least for\n> max_children. I'm not sure about pid since we might call it based on\n> pg_stat_activity..\n\nChanged to ERROR out when the 'max_children' is less than 0.\n\nRegarding pid, I left it untouched considering the consistency with \nother\nsignal sending functions such as pg_cancel_backend().\n\n> + if(!SendProcSignal(pid, PROCSIG_PRINT_MEMORY_CONTEXT, \n> InvalidBackendId))\n> \n> We know the backendid of the process here.\n\nAdded it.\n\n> \n> + if (is_dst_stderr)\n> + {\n> + for (i = 0; i <= level; i++)\n> + fprintf(stderr, \" \");\n> \n> The fprintf path is used nowhere in the patch at all. It can be used\n> while attaching debugger but I'm not sure we need that code. The\n> footprint of this patch is largely shrinked by removing it.\n\nAccording to the past discussion[1], people wanted MemoryContextStats\nas it was, so I think it's better that MemoryContextStats can be used\nas before.\n\n> \n> + strcat(truncated_ident, delimiter);\n> \n> strcpy is sufficient here. And we don't need the delimiter to be a\n> variable. (we can copy a string literal into truncate_ident, then\n> count the length of truncate_ident, instead of the delimiter\n> variable.)\n\nTrue.\n\n> + $current_logfiles = slurp_file($node->data_dir . \n> '/current_logfiles');\n> ...\n> +my $lfname = $current_logfiles;\n> +$lfname =~ s/^stderr //;\n> +chomp $lfname;\n> \n> $node->logfile is the current log file name.\n> \n> + 'target PID is not PostgreSQL server process');\n> \n> Maybe \"check if PID check is working\" or such? And, we can do\n> something like the following to exercise in a more practical way.\n> \n> select pg_print_backend...(pid,) from pg_stat_activity where\n> backend_type = 'checkpointer';\n\nIt seems better.\n\n>> As documented, the current implementation allows that when multiple\n>> pg_print_backend_memory_contexts() called in succession or\n>> simultaneously, max_children can be the one of another\n>> pg_print_backend_memory_contexts().\n>> I had tried to avoid this by adding some state information and using\n>> before_shmem_exit() in case of process termination for cleaning up the\n>> state information as in the patch I presented earlier, but since\n>> kill()\n>> returns success before the dumper called signal handler, it seemed\n>> there were times when we couldn't clean up the state.\n>> Since this happens only when multiple\n>> pg_print_backend_memory_contexts()\n>> are called and their specified number of children are different, and\n>> the\n>> effect is just the not intended number of children to print, it might\n>> be\n>> acceptable.\n> \n> I see it as a non-issue. Even though the behavior looks somewhat\n> strange, that usage is stranger than the behavior.\n\nThanks for your comments!\n\n>> Or it might be better to wait for some seconds if num_chilren on\n>> shared\n>> memory is not the initialized value(meaning some other process is\n>> requesting to print memory contexts).\n>> \n>> >> Only superusers can call pg_print_backend_memory_contexts().\n>> > + /* Only allow superusers to signal superuser-owned backends. */\n>> > + if (superuser_arg(proc->roleId) && !superuser())\n>> > The patch seems to allow even non-superuser to request to print the\n>> > memory\n>> > contexts if the target backend is owned by non-superuser. Is this\n>> > intentional?\n>> > I think that only superuser should be allowed to execute\n>> > pg_print_backend_memory_contexts() whoever owns the target backend.\n>> > Because that function can cause lots of log messages.\n>> \n>> Thanks, it's not intentional, modified it.\n> \n> By the way we can send a procsig to other than a client backend. And\n> most of the postgres processes are using the standard signal handler\n> and intializes the procsig facility. So some of such kind of processes\n> can dump the memory context information as-is. Otherwise we can add\n> CHECK_FOR_INTERRUPT to appropriate place to allow that. I'm not sure\n> how it is useful for other kind of processes, but it might be useful\n> for autovacuum workers.\n\nYeah, I also think it's possible to get memory contexts other than the\nclient backend.\nBut I'm not sure whether people want to do it...\n\n\n[1] https://www.postgresql.org/message-id/906.1513707472%40sss.pgh.pa.us\n\nregards.", "msg_date": "Thu, 25 Mar 2021 00:17:53 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "\n\nOn 2021/03/25 0:17, torikoshia wrote:\n> On 2021-03-23 17:24, Kyotaro Horiguchi wrote:\n> \n> Thanks for reviewing and suggestions!\n\nThe patched version failed to be compiled as follows. Could you fix this issue?\n\nmcxtfuncs.c:22:10: fatal error: utils/mcxtfuncs.h: No such file or directory\n #include \"utils/mcxtfuncs.h\"\n ^~~~~~~~~~~~~~~~~~~\ncompilation terminated.\nmake[4]: *** [<builtin>: mcxtfuncs.o] Error 1\nmake[4]: *** Waiting for unfinished jobs....\nmake[3]: *** [../../../src/backend/common.mk:39: adt-recursive] Error 2\nmake[3]: *** Waiting for unfinished jobs....\nmake[2]: *** [common.mk:39: utils-recursive] Error 2\nmake[1]: *** [Makefile:42: all-backend-recurse] Error 2\nmake: *** [GNUmakefile:11: all-src-recurse] Error 2\n\nhttps://cirrus-ci.com/task/4621477321375744\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 25 Mar 2021 22:02:23 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On 2021-03-25 22:02, Fujii Masao wrote:\n> On 2021/03/25 0:17, torikoshia wrote:\n>> On 2021-03-23 17:24, Kyotaro Horiguchi wrote:\n>> \n>> Thanks for reviewing and suggestions!\n> \n> The patched version failed to be compiled as follows. Could you fix \n> this issue?\n\nSorry, it included a header file that's not contained in\nthe current version patch.\n\nAttached new one.\n\n> mcxtfuncs.c:22:10: fatal error: utils/mcxtfuncs.h: No such file or \n> directory\n> #include \"utils/mcxtfuncs.h\"\n> ^~~~~~~~~~~~~~~~~~~\n> compilation terminated.\n> make[4]: *** [<builtin>: mcxtfuncs.o] Error 1\n> make[4]: *** Waiting for unfinished jobs....\n> make[3]: *** [../../../src/backend/common.mk:39: adt-recursive] Error 2\n> make[3]: *** Waiting for unfinished jobs....\n> make[2]: *** [common.mk:39: utils-recursive] Error 2\n> make[1]: *** [Makefile:42: all-backend-recurse] Error 2\n> make: *** [GNUmakefile:11: all-src-recurse] Error 2\n> \n> https://cirrus-ci.com/task/4621477321375744\n> \n> Regards,", "msg_date": "Thu, 25 Mar 2021 23:45:17 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "At Thu, 25 Mar 2021 23:45:17 +0900, torikoshia <torikoshia@oss.nttdata.com> wrote in \n> Attached new one.\n\nThanks!\n\n- SELECT * FROM pg_get_backend_memory_contexts();\n+ SELECT * FROM pg_get_backend_memory_contexts(0, 0);\n\nHowever we can freely change the signature since it's new in 14, but I\nsee the (void) signature as useful. I vaguely thought of defining\npg_get_backend_memory_contexts(void) in pg_proc.dat then defining\n(int, int) as a different function in system_views.sql. That allows\nthe function of the second signature to output nothing. You can make a\ndistinction between the two signatures by using PG_NARGS() in the C\nfunction.\n\nThat being said, it's somewhat uneasy that two functions with the same\nname returns different values. I'd like to hear others what they feel\nlike about the behavior.\n\n\n+# print memory context of specified backend\n+\n\nThis looks like a garbage.\n\n\n+\tif( pid == 0)\n\nOdd spacing:p\n\n+note \"current_logfiles = $current_logfiles\";\n+\n+like(\n+\t$current_logfiles,\n+\tqr|^stderr log/postgresql-.*log$|,\n+\t'current_logfiles is sane');\n+\n+my $lfname = $current_logfiles;\n+$lfname =~ s/^stderr //;\n+chomp $lfname;\n+\n+my $logfile;\n+my $print_count;\n+\n+# Verify that the backtraces of the processes are logged into logfile.\n+for (my $attempts = 0; $attempts < $max_attempts; $attempts++)\n+{\n+\t$logfile = $node->data_dir . '/' . $lfname;\n\nIt seems that you forgot to include the change on this part in v4.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 26 Mar 2021 12:01:04 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "\n\nOn 2021/03/26 12:01, Kyotaro Horiguchi wrote:\n> At Thu, 25 Mar 2021 23:45:17 +0900, torikoshia <torikoshia@oss.nttdata.com> wrote in\n>> Attached new one.\n\nRegarding the argument max_children, isn't it better to set its default value,\ne.g., 100 like MemoryContextStats() uses?\n\n+\t\tereport(WARNING,\n+\t\t\t\t(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),\n+\t\t\t\t errmsg(\"must be a superuser to log memory contexts\")));\n\nIMO this type of error, i.e., permission error, should be treated as ERROR\nrather than WARNING, like pg_terminate_backend() does.\n\n+\t\tereport(WARNING,\n+\t\t\t\t(errmsg(\"failed to send signal: %m\")));\n\nPer message style rule, \"could not send signal to process %d: %m\" is better?\n\n> Thanks!\n> \n> - SELECT * FROM pg_get_backend_memory_contexts();\n> + SELECT * FROM pg_get_backend_memory_contexts(0, 0);\n> \n> However we can freely change the signature since it's new in 14, but I\n> see the (void) signature as useful. I vaguely thought of defining\n> pg_get_backend_memory_contexts(void) in pg_proc.dat then defining\n> (int, int) as a different function in system_views.sql. That allows\n> the function of the second signature to output nothing. You can make a\n> distinction between the two signatures by using PG_NARGS() in the C\n> function.\n> \n> That being said, it's somewhat uneasy that two functions with the same\n> name returns different values. I'd like to hear others what they feel\n> like about the behavior.\n\nI think that it's confusing to merge two different features into one function.\nIsn't it better to leave pg_get_backend_memory_contexts() as it is, and\nmake the log-memory-contexts feature as separate function, e.g.,\npg_log_backend_memory_contexts()?\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Fri, 26 Mar 2021 12:26:31 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "\n\nOn 2021/03/26 12:26, Fujii Masao wrote:\n> \n> \n> On 2021/03/26 12:01, Kyotaro Horiguchi wrote:\n>> At Thu, 25 Mar 2021 23:45:17 +0900, torikoshia <torikoshia@oss.nttdata.com> wrote in\n>>> Attached new one.\n> \n> Regarding the argument max_children, isn't it better to set its default value,\n> e.g., 100 like MemoryContextStats() uses?\n\n+\tmcxtLogData->maxChildrenPerContext = max_children;\n+\n+\tif(!SendProcSignal(pid, PROCSIG_LOG_MEMORY_CONTEXT, proc->backendId))\n+\t\tPG_RETURN_BOOL(true);\n\nDo we need memory barrier here? Otherwise, there is a race condition\nwhere maxChildrenPerContext has not been set yet when the target backend\nthat received signal read that shared variable. No?\n\n+ Note that when multiple\n+ <function>pg_get_backend_memory_contexts</function> called in\n+ succession or simultaneously, <parameter>max_children</parameter> can\n+ be the one of another\n+ <function>pg_get_backend_memory_contexts</function>.\n+ </para></entry>\n\nThis might not be an issue in practice as Horiguchi-san said upthread.\nBut this looks a bit ugly and might be footgun later. The current approach\nusing shared memory to pass this information to the target backends\nmight be overkill, and too complicated to polish the design at the stage\njust before feature freeze. So I'd withdraw my previous comment and\nam OK to use the hard-coded value as max_children at the first version\nof this feature. Thought?\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Fri, 26 Mar 2021 12:49:16 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "At Fri, 26 Mar 2021 12:26:31 +0900, Fujii Masao <masao.fujii@oss.nttdata.com> wrote in \n> \n> \n> On 2021/03/26 12:01, Kyotaro Horiguchi wrote:\n> > At Thu, 25 Mar 2021 23:45:17 +0900, torikoshia\n> > <torikoshia@oss.nttdata.com> wrote in\n> >> Attached new one.\n> \n> Regarding the argument max_children, isn't it better to set its\n> default value,\n> e.g., 100 like MemoryContextStats() uses?\n> +\t\tereport(WARNING,\n> +\t\t\t\t(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),\n> + errmsg(\"must be a superuser to log memory contexts\")));\n> \n> IMO this type of error, i.e., permission error, should be treated as\n> ERROR\n> rather than WARNING, like pg_terminate_backend() does.\n> +\t\tereport(WARNING,\n> +\t\t\t\t(errmsg(\"failed to send signal: %m\")));\n> \n> Per message style rule, \"could not send signal to process %d: %m\" is\n> better?\n\n+1 x 3 for the above.\n\n> > Thanks!\n> > - SELECT * FROM pg_get_backend_memory_contexts();\n> > + SELECT * FROM pg_get_backend_memory_contexts(0, 0);\n> > However we can freely change the signature since it's new in 14, but I\n> > see the (void) signature as useful. I vaguely thought of defining\n> > pg_get_backend_memory_contexts(void) in pg_proc.dat then defining\n> > (int, int) as a different function in system_views.sql. That allows\n> > the function of the second signature to output nothing. You can make a\n> > distinction between the two signatures by using PG_NARGS() in the C\n> > function.\n> > That being said, it's somewhat uneasy that two functions with the same\n> > name returns different values. I'd like to hear others what they feel\n> > like about the behavior.\n> \n> I think that it's confusing to merge two different features into one\n> function.\n> Isn't it better to leave pg_get_backend_memory_contexts() as it is,\n> and\n> make the log-memory-contexts feature as separate function, e.g.,\n> pg_log_backend_memory_contexts()?\n\nYeah, that name looks better than pg_print_ba.. and I agree to\nseparate the two features. Sorry for wagging the discussion\nback-and-forth.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 26 Mar 2021 12:53:58 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "At Fri, 26 Mar 2021 12:49:16 +0900, Fujii Masao <masao.fujii@oss.nttdata.com> wrote in \n> On 2021/03/26 12:26, Fujii Masao wrote:\n> > On 2021/03/26 12:01, Kyotaro Horiguchi wrote:\n> >> At Thu, 25 Mar 2021 23:45:17 +0900, torikoshia\n> >> <torikoshia@oss.nttdata.com> wrote in\n> >>> Attached new one.\n> > Regarding the argument max_children, isn't it better to set its\n> > default value,\n> > e.g., 100 like MemoryContextStats() uses?\n> \n> +\tmcxtLogData->maxChildrenPerContext = max_children;\n> +\n> + if(!SendProcSignal(pid, PROCSIG_LOG_MEMORY_CONTEXT,\n> proc->backendId))\n> +\t\tPG_RETURN_BOOL(true);\n> \n> Do we need memory barrier here? Otherwise, there is a race condition\n> where maxChildrenPerContext has not been set yet when the target\n> backend\n> that received signal read that shared variable. No?\n> \n> + Note that when multiple\n> + <function>pg_get_backend_memory_contexts</function> called in\n> + succession or simultaneously, <parameter>max_children</parameter>\n> can\n> + be the one of another\n> + <function>pg_get_backend_memory_contexts</function>.\n> + </para></entry>\n> \n> This might not be an issue in practice as Horiguchi-san said upthread.\n> But this looks a bit ugly and might be footgun later. The current\n> approach\n> using shared memory to pass this information to the target backends\n> might be overkill, and too complicated to polish the design at the\n> stage\n> just before feature freeze. So I'd withdraw my previous comment and\n> am OK to use the hard-coded value as max_children at the first version\n> of this feature. Thought?\n\nThe dumper function silently suppresses logging when there are too\nmany children. Suppressing a part of output when the user didn't told\nanything looks like just a misbehavior (even if it is written in the\ndocumentation..), especially when the suppressed contexts occupy the\nmajority of memory usage. I think the fixed-limit of lines works if\nthe lines are in descending order of memory usage.\n\nAt least we need an additional line to inform the suppression.\n\n\"some contexts are omitted\"\n\"n child contexts: total_bytes = ...\"\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 26 Mar 2021 13:17:21 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "At Fri, 26 Mar 2021 13:17:21 +0900 (JST), Kyotaro Horiguchi <horikyota.ntt@gmail.com> wrote in \n> At Fri, 26 Mar 2021 12:49:16 +0900, Fujii Masao <masao.fujii@oss.nttdata.com> wrote in \n> > On 2021/03/26 12:26, Fujii Masao wrote:\n> > > On 2021/03/26 12:01, Kyotaro Horiguchi wrote:\n> > >> At Thu, 25 Mar 2021 23:45:17 +0900, torikoshia\n> > >> <torikoshia@oss.nttdata.com> wrote in\n> > >>> Attached new one.\n> > > Regarding the argument max_children, isn't it better to set its\n> > > default value,\n> > > e.g., 100 like MemoryContextStats() uses?\n> > \n> > +\tmcxtLogData->maxChildrenPerContext = max_children;\n> > +\n> > + if(!SendProcSignal(pid, PROCSIG_LOG_MEMORY_CONTEXT,\n> > proc->backendId))\n> > +\t\tPG_RETURN_BOOL(true);\n> > \n> > Do we need memory barrier here? Otherwise, there is a race condition\n> > where maxChildrenPerContext has not been set yet when the target\n> > backend\n> > that received signal read that shared variable. No?\n> > \n> > + Note that when multiple\n> > + <function>pg_get_backend_memory_contexts</function> called in\n> > + succession or simultaneously, <parameter>max_children</parameter>\n> > can\n> > + be the one of another\n> > + <function>pg_get_backend_memory_contexts</function>.\n> > + </para></entry>\n> > \n> > This might not be an issue in practice as Horiguchi-san said upthread.\n> > But this looks a bit ugly and might be footgun later. The current\n> > approach\n> > using shared memory to pass this information to the target backends\n> > might be overkill, and too complicated to polish the design at the\n> > stage\n> > just before feature freeze. So I'd withdraw my previous comment and\n> > am OK to use the hard-coded value as max_children at the first version\n> > of this feature. Thought?\n> \n> The dumper function silently suppresses logging when there are too\n> many children. Suppressing a part of output when the user didn't told\n> anything looks like just a misbehavior (even if it is written in the\n> documentation..), especially when the suppressed contexts occupy the\n> majority of memory usage. I think the fixed-limit of lines works if\n> the lines are in descending order of memory usage.\n> \n> At least we need an additional line to inform the suppression.\n\n\n> \"some contexts are omitted\"\n> \"n child contexts: total_bytes = ...\"\n\nSorry I missed that is already implemented. So my opnion is I agree\nwith limiting with a fixed-number, and preferablly sorted in\ndescending order of... totalspace/nblocks?\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 26 Mar 2021 13:28:36 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "\n\nOn 2021/03/26 13:28, Kyotaro Horiguchi wrote:\n>> \"some contexts are omitted\"\n>> \"n child contexts: total_bytes = ...\"\n> \n> Sorry I missed that is already implemented. So my opnion is I agree\n> with limiting with a fixed-number, and preferablly sorted in\n> descending order of... totalspace/nblocks?\n\nThis may be an improvement, but makes us modify MemoryContextStatsInternal()\nvery much. I'm afraid that it's too late to do that at this stage...\nWhat about leaving the output order as it is at the first version?\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Fri, 26 Mar 2021 14:02:49 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "At Fri, 26 Mar 2021 14:02:49 +0900, Fujii Masao <masao.fujii@oss.nttdata.com> wrote in \n> \n> \n> On 2021/03/26 13:28, Kyotaro Horiguchi wrote:\n> >> \"some contexts are omitted\"\n> >> \"n child contexts: total_bytes = ...\"\n> > Sorry I missed that is already implemented. So my opnion is I agree\n> > with limiting with a fixed-number, and preferablly sorted in\n> > descending order of... totalspace/nblocks?\n> \n> This may be an improvement, but makes us modify\n> MemoryContextStatsInternal()\n> very much. I'm afraid that it's too late to do that at this stage...\n> What about leaving the output order as it is at the first version?\n\nSo I said \"preferably\":p (with a misspelling...)\nI'm fine with that.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 26 Mar 2021 14:08:51 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On 2021-03-26 14:08, Kyotaro Horiguchi wrote:\n> At Fri, 26 Mar 2021 14:02:49 +0900, Fujii Masao\n> <masao.fujii@oss.nttdata.com> wrote in\n>> \n>> \n>> On 2021/03/26 13:28, Kyotaro Horiguchi wrote:\n>> >> \"some contexts are omitted\"\n>> >> \"n child contexts: total_bytes = ...\"\n>> > Sorry I missed that is already implemented. So my opnion is I agree\n>> > with limiting with a fixed-number, and preferablly sorted in\n>> > descending order of... totalspace/nblocks?\n>> \n>> This may be an improvement, but makes us modify\n>> MemoryContextStatsInternal()\n>> very much. I'm afraid that it's too late to do that at this stage...\n>> What about leaving the output order as it is at the first version?\n> \n> So I said \"preferably\":p (with a misspelling...)\n> I'm fine with that.\n> \n> regards.\n\nThanks for the comments!\n\nAttached a new patch.\n\nIt adds pg_log_backend_memory_contexts(pid) which logs memory contexts\nof the specified backend process.\n\nThe number of child contexts to be logged per parent is limited to 100\nas with MemoryContextStats().\n\nAs written in commit 7b5ef8f2d07, which limits the verbosity of\nmemory context statistics dumps, it supposes that practical cases\nwhere the dump gets long will typically be huge numbers of\nsiblings under the same parent context; while the additional\ndebugging value from seeing details about individual siblings\nbeyond 100 will not be large.\n\nThoughts?\n\n\nRegards.", "msg_date": "Mon, 29 Mar 2021 11:59:13 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "\n\nOn 2021/03/29 11:59, torikoshia wrote:\n> On 2021-03-26 14:08, Kyotaro Horiguchi wrote:\n>> At Fri, 26 Mar 2021 14:02:49 +0900, Fujii Masao\n>> <masao.fujii@oss.nttdata.com> wrote in\n>>>\n>>>\n>>> On 2021/03/26 13:28, Kyotaro Horiguchi wrote:\n>>> >> \"some contexts are omitted\"\n>>> >> \"n child contexts: total_bytes = ...\"\n>>> > Sorry I missed that is already implemented.� So my opnion is I agree\n>>> > with limiting with a fixed-number, and preferablly sorted in\n>>> > descending order of... totalspace/nblocks?\n>>>\n>>> This may be an improvement, but makes us modify\n>>> MemoryContextStatsInternal()\n>>> very much. I'm afraid that it's too late to do that at this stage...\n>>> What about leaving the output order as it is at the first version?\n>>\n>> So I said \"preferably\":p� (with a misspelling...)\n>> I'm fine with that.\n>>\n>> regards.\n> \n> Thanks for the comments!\n> \n> Attached a new patch.\n\nThanks!\n\n> It adds pg_log_backend_memory_contexts(pid) which logs memory contexts\n> of the specified backend process.\n> \n> The number of child contexts to be logged per parent is limited to 100\n> as with MemoryContextStats().\n> \n> As written in commit 7b5ef8f2d07, which limits the verbosity of\n> memory context statistics dumps, it supposes that practical cases\n> where the dump gets long will typically be huge numbers of\n> siblings under the same parent context; while the additional\n> debugging value from seeing details about individual siblings\n> beyond 100 will not be large.\n> \n> Thoughts?\n\nI'm OK with 100. We should comment why we chose 100 for that.\n\nHere are some review comments.\n\nIsn't it better to move HandleProcSignalLogMemoryContext() and\nProcessLogMemoryContextInterrupt() to mcxt.c from procsignal.c\n(like the functions for notify interrupt are defined in async.c)\nbecause they are the functions for memory contexts?\n\n+ * HandleProcSignalLogMemoryContext\n+ *\n+ * Handle receipt of an interrupt indicating log memory context.\n+ * Signal handler portion of interrupt handling.\n\nIMO it's better to comment why we need to separate the function into two,\ni.e., HandleProcSignalLogMemoryContext() and ProcessLogMemoryContextInterrupt(),\nlike the comment for other similar function explains. What about the followings?\n\n-------------------------------\nHandleLogMemoryContextInterrupt\n\nHandle receipt of an interrupt indicating logging of memory contexts.\n\nAll the actual work is deferred to ProcessLogMemoryContextInterrupt(),\nbecause we cannot safely emit a log message inside the signal handler.\n-------------------------------\nProcessLogMemoryContextInterrupt\n\nPerform logging of memory contexts of this backend process.\n\nAny backend that participates in ProcSignal signaling must arrange to\ncall this function if we see LogMemoryContextPending set. It is called\nfrom CHECK_FOR_INTERRUPTS(), which is enough because the target process\nfor logging of memory contexts is a backend.\n-------------------------------\n\n\n+\tif (CheckProcSignal(PROCSIG_LOG_MEMORY_CONTEXT))\n+\t\tHandleProcSignalLogMemoryContext();\n+\n \tif (CheckProcSignal(PROCSIG_BARRIER))\n \t\tHandleProcSignalBarrierInterrupt();\n\nThe code for memory context logging interrupt came after barrier interrupt\nin other places, e.g., procsignal.h. Why is this order of code different?\n\n+/*\n+ * pg_log_backend_memory_contexts\n+ *\t\tPrint memory context of the specified backend process.\n\nIsn't it better to move pg_log_backend_memory_contexts() to mcxtfuncs.c\nfrom mcxt.c because this is the SQL function memory contexts?\n\nIMO we should comment why we allow only superuser to call this function.\nWhat about the following?\n\n-----------------\nSignal a backend process to log its memory contexts.\n\nOnly superusers are allowed to signal to log the memory contexts\nbecause allowing any users to issue this request at an unbounded rate\nwould cause lots of log messages and which can lead to denial of service.\n-----------------\n\n+\tPGPROC\t\t*proc = BackendPidGetProc(pid);\n+\n+\t/* Check whether the target process is PostgreSQL backend process. */\n+\tif (proc == NULL)\n\nWhat about adding more comments as follows?\n\n---------------------------------\n+\t/*\n+\t * BackendPidGetProc returns NULL if the pid isn't valid; but by the time\n+\t * we reach kill(), a process for which we get a valid proc here might\n+\t * have terminated on its own. There's no way to acquire a lock on an\n+\t * arbitrary process to prevent that. But since this mechanism is usually\n+\t * used to debug a backend running and consuming lots of memory,\n+\t * that it might end on its own first and its memory contexts are not\n+\t * logged is not a problem.\n+\t */\n+\tif (proc == NULL)\n+\t{\n+\t\t/*\n+\t\t * This is just a warning so a loop-through-resultset will not abort\n+\t\t * if one backend logged its memory contexts during the run.\n+\t\t */\n+\t\tereport(WARNING,\n---------------------------------\n\n+\t\tereport(ERROR,\n+\t\t\t\t(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),\n+\t\t\t\t errmsg(\"must be a superuser to log memory contexts\")));\n+\t\tPG_RETURN_BOOL(false);\n\nThis PG_RETURN_BOOL(false) is unnecessary because ereport() will emit an ERROR?\n\n+$node->psql('postgres', 'select pg_log_backend_memory_contexts(pg_backend_pid())');\n+\n+my $logfile = slurp_file($node->logfile);\n+like($logfile, qr/Grand total: \\d+ bytes in \\d+ blocks/,\n+\t\t'found expected memory context print in the log file');\n\nIsn't there the case where the memory contexts have not been logged yet\nwhen slurp_file() is called? It's rare, though. If there is the risk for that,\nwe should wait for the memory contexts to be actually logged?\n\nBTW, I agree that we should have the regression test that calls\npg_log_backend_memory_contexts() and checks, e.g., that it doesn't cause\nsegmentation fault. But I'm just wondering if it's a bit overkill to make perl\nscriptand start new node to test only this function...\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Tue, 30 Mar 2021 02:28:51 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On 2021-03-30 02:28, Fujii Masao wrote:\n\nThanks for reviewing and kind suggestions!\n\n>> It adds pg_log_backend_memory_contexts(pid) which logs memory contexts\n>> of the specified backend process.\n>> \n>> The number of child contexts to be logged per parent is limited to 100\n>> as with MemoryContextStats().\n>> \n>> As written in commit 7b5ef8f2d07, which limits the verbosity of\n>> memory context statistics dumps, it supposes that practical cases\n>> where the dump gets long will typically be huge numbers of\n>> siblings under the same parent context; while the additional\n>> debugging value from seeing details about individual siblings\n>> beyond 100 will not be large.\n>> \n>> Thoughts?\n> \n> I'm OK with 100. We should comment why we chose 100 for that.\n\nAdded following comments.\n\n+ /*\n+ * When a backend process is consuming huge memory, logging all \nits\n+ * memory contexts might overrun available disk space. To \nprevent\n+ * this, we limit the number of child contexts per parent to \n100.\n+ *\n+ * As with MemoryContextStats(), we suppose that practical cases\n+ * where the dump gets long will typically be huge numbers of\n+ * siblings under the same parent context; while the additional\n+ * debugging value from seeing details about individual siblings\n+ * beyond 100 will not be large.\n+ */\n+ MemoryContextStatsDetail(TopMemoryContext, 100, false);\n\n> \n> Here are some review comments.\n> \n> Isn't it better to move HandleProcSignalLogMemoryContext() and\n> ProcessLogMemoryContextInterrupt() to mcxt.c from procsignal.c\n> (like the functions for notify interrupt are defined in async.c)\n> because they are the functions for memory contexts?\n\nAgreed.\nAlso renamed HandleProcSignalLogMemoryContext to\nHandleLogMemoryContextInterrupt.\n\n> + * HandleProcSignalLogMemoryContext\n> + *\n> + * Handle receipt of an interrupt indicating log memory context.\n> + * Signal handler portion of interrupt handling.\n> \n> IMO it's better to comment why we need to separate the function into \n> two,\n> i.e., HandleProcSignalLogMemoryContext() and \n> ProcessLogMemoryContextInterrupt(),\n> like the comment for other similar function explains. What about the \n> followings?\n\nThanks! Changed them to the suggested one.\n\n> -------------------------------\n> HandleLogMemoryContextInterrupt\n> \n> Handle receipt of an interrupt indicating logging of memory contexts.\n> \n> All the actual work is deferred to ProcessLogMemoryContextInterrupt(),\n> because we cannot safely emit a log message inside the signal handler.\n> -------------------------------\n> ProcessLogMemoryContextInterrupt\n> \n> Perform logging of memory contexts of this backend process.\n> \n> Any backend that participates in ProcSignal signaling must arrange to\n> call this function if we see LogMemoryContextPending set. It is called\n> from CHECK_FOR_INTERRUPTS(), which is enough because the target process\n> for logging of memory contexts is a backend.\n> -------------------------------\n> \n> \n> +\tif (CheckProcSignal(PROCSIG_LOG_MEMORY_CONTEXT))\n> +\t\tHandleProcSignalLogMemoryContext();\n> +\n> \tif (CheckProcSignal(PROCSIG_BARRIER))\n> \t\tHandleProcSignalBarrierInterrupt();\n> \n> The code for memory context logging interrupt came after barrier \n> interrupt\n> in other places, e.g., procsignal.h. Why is this order of code \n> different?\n\nFixed.\n\n> +/*\n> + * pg_log_backend_memory_contexts\n> + *\t\tPrint memory context of the specified backend process.\n> \n> Isn't it better to move pg_log_backend_memory_contexts() to mcxtfuncs.c\n> from mcxt.c because this is the SQL function memory contexts?\n\nAgreed.\n\n> IMO we should comment why we allow only superuser to call this \n> function.\n> What about the following?\n\nThanks!\nModified the patch according to the suggestions.\n\n> -----------------\n> Signal a backend process to log its memory contexts.\n> \n> Only superusers are allowed to signal to log the memory contexts\n> because allowing any users to issue this request at an unbounded rate\n> would cause lots of log messages and which can lead to denial of \n> service.\n> -----------------\n> \n> +\tPGPROC\t\t*proc = BackendPidGetProc(pid);\n> +\n> +\t/* Check whether the target process is PostgreSQL backend process. */\n> +\tif (proc == NULL)\n> \n> What about adding more comments as follows?\n> \n> ---------------------------------\n> +\t/*\n> +\t * BackendPidGetProc returns NULL if the pid isn't valid; but by the \n> time\n> +\t * we reach kill(), a process for which we get a valid proc here \n> might\n> +\t * have terminated on its own. There's no way to acquire a lock on \n> an\n> +\t * arbitrary process to prevent that. But since this mechanism is \n> usually\n> +\t * used to debug a backend running and consuming lots of memory,\n> +\t * that it might end on its own first and its memory contexts are not\n> +\t * logged is not a problem.\n> +\t */\n> +\tif (proc == NULL)\n> +\t{\n> +\t\t/*\n> +\t\t * This is just a warning so a loop-through-resultset will not abort\n> +\t\t * if one backend logged its memory contexts during the run.\n> +\t\t */\n> +\t\tereport(WARNING,\n> ---------------------------------\n> \n> +\t\tereport(ERROR,\n> +\t\t\t\t(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),\n> +\t\t\t\t errmsg(\"must be a superuser to log memory contexts\")));\n> +\t\tPG_RETURN_BOOL(false);\n> \n> This PG_RETURN_BOOL(false) is unnecessary because ereport() will emit \n> an ERROR?\n> \n> +$node->psql('postgres', 'select\n> pg_log_backend_memory_contexts(pg_backend_pid())');\n> +\n> +my $logfile = slurp_file($node->logfile);\n> +like($logfile, qr/Grand total: \\d+ bytes in \\d+ blocks/,\n> +\t\t'found expected memory context print in the log file');\n> \n> Isn't there the case where the memory contexts have not been logged yet\n> when slurp_file() is called? It's rare, though. If there is the risk \n> for that,\n> we should wait for the memory contexts to be actually logged?\n> \n> BTW, I agree that we should have the regression test that calls\n> pg_log_backend_memory_contexts() and checks, e.g., that it doesn't \n> cause\n> segmentation fault. But I'm just wondering if it's a bit overkill to \n> make perl\n> scriptand start new node to test only this function...\n\nOK, I removed the perl TAP test and added a regression test running \npg_log_backend_memory_contexts(pg_backend_pid()) and checking it returns \n't'.\n\n\nRegards.", "msg_date": "Tue, 30 Mar 2021 22:06:58 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On 2021/03/30 22:06, torikoshia wrote:\n> Modified the patch according to the suggestions.\n\nThanks for updating the patch!\n\nI applied the cosmetic changes to the patch and added the example of\nthe function call into the document. Attached is the updated version\nof the patch. Could you check this version?\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION", "msg_date": "Wed, 31 Mar 2021 04:36:07 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On 2021-03-31 04:36, Fujii Masao wrote:\n> On 2021/03/30 22:06, torikoshia wrote:\n>> Modified the patch according to the suggestions.\n> \n> Thanks for updating the patch!\n> \n> I applied the cosmetic changes to the patch and added the example of\n> the function call into the document. Attached is the updated version\n> of the patch. Could you check this version?\n> \n\nThanks a lot!\n\n\n+The memory contexts will be logged in the log file. For example:\n\nWhen 'log_destination = stderr' and 'logging_collector = off', it does\nnot log in the file but in the stderr.\n\nDescription like below would be a bit more accurate but I'm wondering\nit's repeating the same words.\n\n+ The memory contexts will be logged based on the log configuration set. \nFor example:\n\nHow do you think?\n\n\n+<programlisting>\n+postgres=# SELECT pg_log_backend_memory_contexts(pg_backend_pid());\n+ pg_log_backend_memory_contexts\n+--------------------------------\n+ t\n+(1 row)\n+\n+The memory contexts will be logged in the log file. For example:\n+LOG: logging memory contexts of PID 10377\n+STATEMENT: SELECT pg_log_backend_memory_contexts(pg_backend_pid());\n+LOG: level: 0; TopMemoryContext: 80800 total in 6 blocks; 14432 free \n(5 chunks); 66368 used\n+LOG: level: 1; pgstat TabStatusArray lookup hash table: 8192 total in \n1 blocks; 1408 free (0 chunks); 6784 used\n\nThe line \"The memory contexts will be logged in the log file. For \nexample:\"\nis neither nor SQL command and its outputs, it might be better to\ndifferentiate it.\n\n\nWhat about the following like attached patch?\n\n+<programlisting>\n+postgres=# SELECT pg_log_backend_memory_contexts(pg_backend_pid());\n+ pg_log_backend_memory_contexts\n+--------------------------------\n+ t\n+(1 row)\n+</programlisting>\n+The memory contexts will be logged in the log file. For example:\n+<screen>\n+LOG: logging memory contexts of PID 10377\n+STATEMENT: SELECT pg_log_backend_memory_contexts(pg_backend_pid());\n+LOG: level: 0; TopMemoryContext: 80800 total in 6 blocks; 14432 free \n(5 chunks); 66368 used\n+LOG: level: 1; pgstat TabStatusArray lookup hash table: 8192 total in \n1 blocks; 1408 free (0 chunks); 6784 used\n...(snip)...\n+LOG: level: 1; ErrorContext: 8192 total in 1 blocks; 7928 free (3 \nchunks); 264 used\n+LOG: Grand total: 1651920 bytes in 201 blocks; 622360 free (88 \nchunks); 1029560 used\n+</screen>\n\n\nRegards.", "msg_date": "Wed, 31 Mar 2021 15:02:02 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "At Wed, 31 Mar 2021 15:02:02 +0900, torikoshia <torikoshia@oss.nttdata.com> wrote in \n> On 2021-03-31 04:36, Fujii Masao wrote:\n> > On 2021/03/30 22:06, torikoshia wrote:\n> >> Modified the patch according to the suggestions.\n> > Thanks for updating the patch!\n> > I applied the cosmetic changes to the patch and added the example of\n> > the function call into the document. Attached is the updated version\n> > of the patch. Could you check this version?\n> > \n> \n> Thanks a lot!\n> \n> \n> +The memory contexts will be logged in the log file. For example:\n> \n> When 'log_destination = stderr' and 'logging_collector = off', it does\n> not log in the file but in the stderr.\n> \n> Description like below would be a bit more accurate but I'm wondering\n> it's repeating the same words.\n> \n> + The memory contexts will be logged based on the log configuration\n> set. For example:\n> \n> How do you think?\n\nHow about \"The memory contexts will be logged in the server log\" ?\nI think \"server log\" doesn't suggest any concrete target.\n\n> +<programlisting>\n> +postgres=# SELECT pg_log_backend_memory_contexts(pg_backend_pid());\n> + pg_log_backend_memory_contexts\n> +--------------------------------\n> + t\n> +(1 row)\n> +\n> +The memory contexts will be logged in the log file. For example:\n> +LOG: logging memory contexts of PID 10377\n> +STATEMENT: SELECT pg_log_backend_memory_contexts(pg_backend_pid());\n> +LOG: level: 0; TopMemoryContext: 80800 total in 6 blocks; 14432 free\n> (5 chunks); 66368 used\n> +LOG: level: 1; pgstat TabStatusArray lookup hash table: 8192 total in\n> 1 blocks; 1408 free (0 chunks); 6784 used\n> \n> The line \"The memory contexts will be logged in the log file. For\n> example:\"\n> is neither nor SQL command and its outputs, it might be better to\n> differentiate it.\n> \n> \n> What about the following like attached patch?\n> \n> +<programlisting>\n> +postgres=# SELECT pg_log_backend_memory_contexts(pg_backend_pid());\n> + pg_log_backend_memory_contexts\n> +--------------------------------\n> + t\n> +(1 row)\n> +</programlisting>\n> +The memory contexts will be logged in the log file. For example:\n> +<screen>\n> +LOG: logging memory contexts of PID 10377\n> +STATEMENT: SELECT pg_log_backend_memory_contexts(pg_backend_pid());\n> +LOG: level: 0; TopMemoryContext: 80800 total in 6 blocks; 14432 free\n> (5 chunks); 66368 used\n> +LOG: level: 1; pgstat TabStatusArray lookup hash table: 8192 total in\n> 1 blocks; 1408 free (0 chunks); 6784 used\n> ...(snip)...\n> +LOG: level: 1; ErrorContext: 8192 total in 1 blocks; 7928 free (3\n> chunks); 264 used\n> +LOG: Grand total: 1651920 bytes in 201 blocks; 622360 free (88\n> chunks); 1029560 used\n> +</screen>\n\n+1 from me. It looks like more compliant with the standard?\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Wed, 31 Mar 2021 15:16:12 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "\n\nOn 2021/03/31 15:16, Kyotaro Horiguchi wrote:\n>> + The memory contexts will be logged based on the log configuration\n>> set. For example:\n>>\n>> How do you think?\n> \n> How about \"The memory contexts will be logged in the server log\" ?\n> I think \"server log\" doesn't suggest any concrete target.\n\nOr just using \"logged\" is enough?\n\nAlso I'd like to document that one message for each memory context is logged.\nSo what about the following?\n\n One message for each memory context will be logged. For example,\n\n\n> +1 from me. It looks like more compliant with the standard?\n\n+1, too.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 1 Apr 2021 19:13:05 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On 2021-04-01 19:13, Fujii Masao wrote:\n> On 2021/03/31 15:16, Kyotaro Horiguchi wrote:\n>>> + The memory contexts will be logged based on the log configuration\n>>> set. For example:\n>>> \n>>> How do you think?\n>> \n>> How about \"The memory contexts will be logged in the server log\" ?\n>> I think \"server log\" doesn't suggest any concrete target.\n> \n> Or just using \"logged\" is enough?\n> \n> Also I'd like to document that one message for each memory context is \n> logged.\n> So what about the following?\n> \n> One message for each memory context will be logged. For example,\n\n\nAgreed.\n\nBTW, there was a conflict since c30f54ad732(Detect POLLHUP/POLLRDHUP \nwhile\nrunning queries), attached v9.\n\n\nRegards,", "msg_date": "Mon, 05 Apr 2021 11:55:47 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On Sun, Apr 4, 2021 at 7:56 PM torikoshia <torikoshia@oss.nttdata.com>\nwrote:\n\n> On 2021-04-01 19:13, Fujii Masao wrote:\n> > On 2021/03/31 15:16, Kyotaro Horiguchi wrote:\n> >>> + The memory contexts will be logged based on the log configuration\n> >>> set. For example:\n> >>>\n> >>> How do you think?\n> >>\n> >> How about \"The memory contexts will be logged in the server log\" ?\n> >> I think \"server log\" doesn't suggest any concrete target.\n> >\n> > Or just using \"logged\" is enough?\n> >\n> > Also I'd like to document that one message for each memory context is\n> > logged.\n> > So what about the following?\n> >\n> > One message for each memory context will be logged. For example,\n>\n>\n> Agreed.\n>\n> BTW, there was a conflict since c30f54ad732(Detect POLLHUP/POLLRDHUP\n> while\n> running queries), attached v9.\n>\n>\n> Regards,\n\n\nHi,\n\n+ * On receipt of this signal, a backend sets the flag in the signal\n+ * handler, and then which causes the next CHECK_FOR_INTERRUPTS()\n\nI think the 'and then' is not needed:\n\n handler which causes the next ...\n\n+ * This is just a warning so a loop-through-resultset will not abort\n+ * if one backend logged its memory contexts during the run.\n\nThe pid given by arg 0 is not a PostgreSQL server process. Which other\nbackend could it be ?\n\nThanks\n\nOn Sun, Apr 4, 2021 at 7:56 PM torikoshia <torikoshia@oss.nttdata.com> wrote:On 2021-04-01 19:13, Fujii Masao wrote:\n> On 2021/03/31 15:16, Kyotaro Horiguchi wrote:\n>>> + The memory contexts will be logged based on the log configuration\n>>> set. For example:\n>>> \n>>> How do you think?\n>> \n>> How about \"The memory contexts will be logged in the server log\" ?\n>> I think \"server log\" doesn't suggest any concrete target.\n> \n> Or just using \"logged\" is enough?\n> \n> Also I'd like to document that one message for each memory context is \n> logged.\n> So what about the following?\n> \n>     One message for each memory context will be logged. For example,\n\n\nAgreed.\n\nBTW, there was a conflict since c30f54ad732(Detect POLLHUP/POLLRDHUP \nwhile\nrunning queries), attached v9.\n\n\nRegards,Hi,+ * On receipt of this signal, a backend sets the flag in the signal+ * handler, and then which causes the next CHECK_FOR_INTERRUPTS()I think the 'and then' is not needed:  handler which causes the next ...+        * This is just a warning so a loop-through-resultset will not abort+        * if one backend logged its memory contexts during the run.The pid given by arg 0 is not a PostgreSQL server process. Which other backend could it be ?Thanks", "msg_date": "Sun, 4 Apr 2021 20:20:36 -0700", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "\n\nOn 2021/04/05 12:20, Zhihong Yu wrote:\n> +        * This is just a warning so a loop-through-resultset will not abort\n> +        * if one backend logged its memory contexts during the run.\n> \n> The pid given by arg 0 is not a PostgreSQL server process. Which other backend could it be ?\n\nThis is the comment that I added wrongly. So the comment should be\n\"This is just a warning so a loop-through-resultset will not abort\nif one backend terminated on its own during the run.\",\nlike pg_signal_backend(). Thought?\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Mon, 5 Apr 2021 12:59:14 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On 2021-04-05 12:59, Fujii Masao wrote:\n> On 2021/04/05 12:20, Zhihong Yu wrote:\n\nThanks for reviewing!\n\n>> + * On receipt of this signal, a backend sets the flag in the signal\n>> + * handler, and then which causes the next CHECK_FOR_INTERRUPTS()\n\n>> I think the 'and then' is not needed:\n\nAlthough I wonder either would be fine, removed the words.\n\n>> +        * This is just a warning so a loop-through-resultset will not \n>> abort\n>> +        * if one backend logged its memory contexts during the run.\n>> \n>> The pid given by arg 0 is not a PostgreSQL server process. Which other \n>> backend could it be ?\n> \n> This is the comment that I added wrongly. So the comment should be\n> \"This is just a warning so a loop-through-resultset will not abort\n> if one backend terminated on its own during the run.\",\n> like pg_signal_backend(). Thought?\n\n+1.\n\nAttached v10 patch.\n\n\nRegards,", "msg_date": "Mon, 05 Apr 2021 21:03:12 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On 2021/04/05 21:03, torikoshia wrote:\n> On 2021-04-05 12:59, Fujii Masao wrote:\n>> On 2021/04/05 12:20, Zhihong Yu wrote:\n> \n> Thanks for reviewing!\n> \n>>> + * On receipt of this signal, a backend sets the flag in the signal\n>>> + * handler, and then which causes the next CHECK_FOR_INTERRUPTS()\n> \n>>> I think the 'and then' is not needed:\n> \n> Although I wonder either would be fine, removed the words.\n> \n>>> +        * This is just a warning so a loop-through-resultset will not abort\n>>> +        * if one backend logged its memory contexts during the run.\n>>>\n>>> The pid given by arg 0 is not a PostgreSQL server process. Which other backend could it be ?\n>>\n>> This is the comment that I added wrongly. So the comment should be\n>> \"This is just a warning so a loop-through-resultset will not abort\n>> if one backend terminated on its own during the run.\",\n>> like pg_signal_backend(). Thought?\n> \n> +1.\n> \n> Attached v10 patch.\n\nThanks for updating the patch!\n\nI updated the patch as follows. Could you check the attached patch?\n\n+ Memory contexts will be logged based on the log configuration set.\n+ See <xref linkend=\"runtime-config-logging\"/> for more information.\n\nThose memory contexts are logged at LOG level, but they are not sent to\na client whatever the setting of client_min_messages. I think\nthis information should be documented. So I updated the document as follows.\n\n These memory contexts will be logged at <literal>LOG</literal>\n message level. They will appear in the server log based on\n the log configuration set (See <xref linkend=\"runtime-config-logging\"/>\n for more information), but will not be sent to the client whatever\n the setting of <xref linkend=\"guc-client-min-messages\"/>.\n\n+ Only superusers can log the memory contexts.\n\nWe can read this description as \"only superusers can request to log ...\".\nBut ISTM that we can also read this as \"only superusers can log (dump)\nthe memory contexts of its backend\". Right? To avoid this confusion,\nI updated this description as follows.\n\n Only superusers can request to log the memory contexts.\n\nI added the following note about the performance overhead by this function.\n\n Note that frequent calls to this function could incur significant overhead,\n because it may generate a large number of log messages.\n\nI also added some comments.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION", "msg_date": "Tue, 6 Apr 2021 00:08:46 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "On 2021-04-06 00:08, Fujii Masao wrote:\n> On 2021/04/05 21:03, torikoshia wrote:\n>> On 2021-04-05 12:59, Fujii Masao wrote:\n>>> On 2021/04/05 12:20, Zhihong Yu wrote:\n>> \n>> Thanks for reviewing!\n>> \n>>>> + * On receipt of this signal, a backend sets the flag in the signal\n>>>> + * handler, and then which causes the next CHECK_FOR_INTERRUPTS()\n>> \n>>>> I think the 'and then' is not needed:\n>> \n>> Although I wonder either would be fine, removed the words.\n>> \n>>>> +        * This is just a warning so a loop-through-resultset will \n>>>> not abort\n>>>> +        * if one backend logged its memory contexts during the run.\n>>>> \n>>>> The pid given by arg 0 is not a PostgreSQL server process. Which \n>>>> other backend could it be ?\n>>> \n>>> This is the comment that I added wrongly. So the comment should be\n>>> \"This is just a warning so a loop-through-resultset will not abort\n>>> if one backend terminated on its own during the run.\",\n>>> like pg_signal_backend(). Thought?\n>> \n>> +1.\n>> \n>> Attached v10 patch.\n> \n> Thanks for updating the patch!\n> \n> I updated the patch as follows. Could you check the attached patch?\n\nThanks a lot!\n\nI don't have any objections to your improvements.\n\nRegards,\n\n\n", "msg_date": "Tue, 06 Apr 2021 10:57:01 +0900", "msg_from": "torikoshia <torikoshia@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" }, { "msg_contents": "\n\nOn 2021/04/06 10:57, torikoshia wrote:\n> I don't have any objections to your improvements.\n\nThanks for the check! I pushed the patch. Thanks a lot!\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Tue, 6 Apr 2021 13:46:59 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Get memory contexts of an arbitrary backend process" } ]
[ { "msg_contents": "Currently pg_list.h doesn't have a variant for uint32 list (like\nT_UIntList), is there a reason other than that that we don't need it\ntill now? I see that one can use T_OidList instead (as Oid is uint32)\nbut I am not sure if that is a good idea to say use it for maintaining\na list of TransactionIds. We need to use such a variant of T_UIntlist\nat one place in the patch for the \"streaming of in-progress\ntransactions\" [1].\n\nThe current use case is as below:\n\ntypedef struct RelationSyncEntry\n{\n..\nList *streamed_txns; /* streamed toplevel transactions with this\n* schema */\n\n/*\n * We expect relatively small number of streamed transactions.\n */\nstatic bool\nget_schema_sent_in_streamed_txn(RelationSyncEntry *entry, TransactionId xid)\n{\n..\nforeach (lc, entry->streamed_txns)\n{\nif (xid == lfirst_int(lc))\nreturn true;\n}\n..\n}\n\n/*\n * Add the xid in the rel sync entry for which we have already sent the schema\n * of the relation.\n */\nstatic void\nset_schema_sent_in_streamed_txn(RelationSyncEntry *entry, TransactionId xid)\n{\n..\nentry->streamed_txns = lappend_int(entry->streamed_txns, xid);\n..\n}\n\nNow, as far as I can see there is no problem in using T_IntList in\nsuch usage because we are not going to fetch stored unsigned value as\na signed value, so the comparison in get_schema_sent_in_streamed_txn\nshould work well. However, still, I thought it would be better if\nthere is a built-in T_UIntList.\n\nThoughts?\n\n[1] - https://www.postgresql.org/message-id/CAFiTN-u_4uvGjAPO536m-YsR%2Bk9J-%3Dwqx2K9CtrFOHcJPa7Szg%40mail.gmail.com\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Mon, 31 Aug 2020 16:59:06 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": true, "msg_subject": "Use T_IntList for uint32" }, { "msg_contents": "On Mon, Aug 31, 2020 at 4:59 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> Now, as far as I can see there is no problem in using T_IntList in\n> such usage because we are not going to fetch stored unsigned value as\n> a signed value, so the comparison in get_schema_sent_in_streamed_txn\n> should work well. However, still, I thought it would be better if\n> there is a built-in T_UIntList.\n>\n> Thoughts?\n\nMay be we should have separate list APIs for XID like OID, in case we\nchange underlying datatype of XID in future (unlikely but we have had\ndiscussion about 64bit XIDs in the past). Apart from that it helps us\ntrack code which deals with XID lists.\n\n\n-- \nBest Wishes,\nAshutosh Bapat\n\n\n", "msg_date": "Mon, 31 Aug 2020 17:44:03 +0530", "msg_from": "Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Use T_IntList for uint32" }, { "msg_contents": "Amit Kapila <amit.kapila16@gmail.com> writes:\n> Currently pg_list.h doesn't have a variant for uint32 list (like\n> T_UIntList), is there a reason other than that that we don't need it\n> till now?\n\nI'm not in favor of adding another list variant code just for that;\nthe overhead is nonzero, and the gain negligible. (I think the reason\nwe have OID lists is the idea that someday we'd want to make OID 64-bit.\nA list type defined as \"UInt\" would offer no such future-proofing.)\n\nThe code you quote probably ought to be casting the result of lfirst_int\nto uint32, but I see no reason to work harder.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 31 Aug 2020 09:28:43 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Use T_IntList for uint32" }, { "msg_contents": "On Mon, Aug 31, 2020 at 6:58 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Amit Kapila <amit.kapila16@gmail.com> writes:\n> > Currently pg_list.h doesn't have a variant for uint32 list (like\n> > T_UIntList), is there a reason other than that that we don't need it\n> > till now?\n>\n> I'm not in favor of adding another list variant code just for that;\n> the overhead is nonzero, and the gain negligible. (I think the reason\n> we have OID lists is the idea that someday we'd want to make OID 64-bit.\n> A list type defined as \"UInt\" would offer no such future-proofing.)\n>\n\nI agree with this and I also don't want to add more code for this\nunless it is really required. Having said that, the case for Xids is\nsimilar to Oids where someday we might want it to be 64-bit but we can\nleave it for another day.\n\n> The code you quote probably ought to be casting the result of lfirst_int\n> to uint32, but I see no reason to work harder.\n>\n\nSounds reasonable, will use this for now.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 1 Sep 2020 08:51:28 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Use T_IntList for uint32" }, { "msg_contents": "On Mon, Aug 31, 2020 at 5:44 PM Ashutosh Bapat\n<ashutosh.bapat.oss@gmail.com> wrote:\n>\n> On Mon, Aug 31, 2020 at 4:59 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> > Now, as far as I can see there is no problem in using T_IntList in\n> > such usage because we are not going to fetch stored unsigned value as\n> > a signed value, so the comparison in get_schema_sent_in_streamed_txn\n> > should work well. However, still, I thought it would be better if\n> > there is a built-in T_UIntList.\n> >\n> > Thoughts?\n>\n> May be we should have separate list APIs for XID like OID, in case we\n> change underlying datatype of XID in future (unlikely but we have had\n> discussion about 64bit XIDs in the past). Apart from that it helps us\n> track code which deals with XID lists.\n>\n\nThis is a valid point but I think for now I will go with Tom's\nsuggestion as the demand for this seems low at this stage. I don't\nwant to introduce a new set of APIs just for one use case especially\nwhen we can work with existing APIs.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 1 Sep 2020 08:53:33 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Use T_IntList for uint32" }, { "msg_contents": "Amit Kapila <amit.kapila16@gmail.com> writes:\n> On Mon, Aug 31, 2020 at 5:44 PM Ashutosh Bapat\n> <ashutosh.bapat.oss@gmail.com> wrote:\n>> May be we should have separate list APIs for XID like OID, in case we\n>> change underlying datatype of XID in future (unlikely but we have had\n>> discussion about 64bit XIDs in the past). Apart from that it helps us\n>> track code which deals with XID lists.\n\n> This is a valid point but I think for now I will go with Tom's\n> suggestion as the demand for this seems low at this stage. I don't\n> want to introduce a new set of APIs just for one use case especially\n> when we can work with existing APIs.\n\nI've occasionally wondered about having exactly two physical List\nimplementations, one for 32-bit payloads and one for 64-bit payloads, and\nthen putting a trivial macros-or-static-inlines layer in front of that\nthat uses casts to supply variants for pointers, signed ints, unsigned\nints, etc etc. There hasn't yet been enough reason to pursue doing it\nthough.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 01 Sep 2020 01:27:15 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Use T_IntList for uint32" }, { "msg_contents": "On Tue, Sep 01, 2020 at 01:27:15AM -0400, Tom Lane wrote:\n> I've occasionally wondered about having exactly two physical List\n> implementations, one for 32-bit payloads and one for 64-bit payloads, and\n> then putting a trivial macros-or-static-inlines layer in front of that\n> that uses casts to supply variants for pointers, signed ints, unsigned\n> ints, etc etc. There hasn't yet been enough reason to pursue doing it\n> though.\n\nFWIW, moving pg_list.h & co to have just two list implementations, based\non say bits32 and a new bits64 is something I was thinking about while\nreading this thread.\n--\nMichael", "msg_date": "Tue, 1 Sep 2020 14:56:35 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Use T_IntList for uint32" } ]
[ { "msg_contents": "Hi,\n\nIt seems like this patch is nearly finished. I fixed all the remaining\nissues. I'm also asking\na confirmation of the test scenarios you want to see in the next\nversion of the patch.\n\n> Hi,\n>\n> On 2020-07-10 19:01:49 -0400, Alvaro Herrera wrote:\n> > Totally unasked for, here's a rebase of this patch series. I didn't do\n> > anything other than rebasing to current master, solving a couple of very\n> > trivial conflicts, fixing some whitespace complaints by git apply, and\n> > running tests to verify everthing works.\n> >\n> > I don't foresee working on this at all, so if anyone is interested in\n> > seeing this feature in, I encourage them to read and address\n> > Horiguchi-san's feedback.\n>\n> Nor am I planning to do so, but I do think its a pretty important\n> improvement.\n>\n>\nFixed\n\n>\n>\n> > +/*\n> > + * PQrecyclePipelinedCommand\n> > + * Push a command queue entry onto the freelist. It must be a dangling entry\n> > + * with null next pointer and not referenced by any other entry's next pointer.\n> > + */\n>\n> Dangling sounds a bit like it's already freed.\n>\n>\nFixed\n\n>\n>\n> > +/*\n> > + * PQbatchSendQueue\n> > + * End a batch submission by sending a protocol sync. The connection will\n> > + * remain in batch mode and unavailable for new synchronous command execution\n> > + * functions until all results from the batch are processed by the client.\n>\n> I feel like the reference to the protocol sync is a bit too low level\n> for an external API. It should first document what the function does\n> from a user's POV.\n>\n> I think it'd also be good to document whether / whether not queries can\n> already have been sent before PQbatchSendQueue is called or not.\n>\nFixed\n\n>\n>\n>\n> > + if (conn->batch_status == PQBATCH_MODE_ABORTED && conn->queryclass != PGQUERY_SYNC)\n> > + {\n> > + /*\n> > + * In an aborted batch we don't get anything from the server for each\n> > + * result; we're just discarding input until we get to the next sync\n> > + * from the server. The client needs to know its queries got aborted\n> > + * so we create a fake PGresult to return immediately from\n> > + * PQgetResult.\n> > + */\n> > + conn->result = PQmakeEmptyPGresult(conn,\n> > + PGRES_BATCH_ABORTED);\n> > + if (!conn->result)\n> > + {\n> > + printfPQExpBuffer(&conn->errorMessage,\n> > + libpq_gettext(\"out of memory\"));\n> > + pqSaveErrorResult(conn);\n> > + return 0;\n>\n> Is there any way an application can recover at this point? ISTM we'd be\n> stuck in the previous asyncStatus, no?\n>\n\nconn->result is null when malloc(sizeof(PGresult)) returns null. It's\nvery unlikely unless\nthe server machine is out of memory, so the server will probably be\nunresponsive anyway.\n\nI'm leaving this as it is but if anyone has a solution simple to\nimplement I'll fix it.\n\n>\n>\n> > +/* pqBatchFlush\n> > + * In batch mode, data will be flushed only when the out buffer reaches the threshold value.\n> > + * In non-batch mode, data will be flushed all the time.\n> > + */\n> > +static int\n> > +pqBatchFlush(PGconn *conn)\n> > +{\n> > + if ((conn->batch_status == PQBATCH_MODE_OFF)||(conn->outCount >= OUTBUFFER_THRESHOLD))\n> > + return(pqFlush(conn));\n> > + return 0; /* Just to keep compiler quiet */\n> > +}\n>\n> unnecessarily long line.\n>\nFixed\n\n>\n> > +/*\n> > + * Connection's outbuffer threshold is set to 64k as it is safe\n> > + * in Windows as per comments in pqSendSome() API.\n> > + */\n> > +#define OUTBUFFER_THRESHOLD 65536\n>\n> I don't think the comment explains much. It's fine to send more than 64k\n> with pqSendSome(), they'll just be send with separate pgsecure_write()\n> invocations. And only on windows.\n>\n> It clearly makes sense to start sending out data at a certain\n> granularity to avoid needing unnecessary amounts of memory, and to make\n> more efficient use of latency / serer side compute.\n>\n> It's not implausible that 64k is the right amount for that, I just don't\n> think the explanation above is good.\n>\n\nFixed\n\n> > diff --git a/src/test/modules/test_libpq/testlibpqbatch.c b/src/test/modules/test_libpq/testlibpqbatch.c\n> > new file mode 100644\n> > index 0000000000..4d6ba266e5\n> > --- /dev/null\n> > +++ b/src/test/modules/test_libpq/testlibpqbatch.c\n> > @@ -0,0 +1,1456 @@\n> > +/*\n> > + * src/test/modules/test_libpq/testlibpqbatch.c\n> > + *\n> > + *\n> > + * testlibpqbatch.c\n> > + * Test of batch execution functionality\n> > + */\n> > +\n> > +#ifdef WIN32\n> > +#include <windows.h>\n> > +#endif\n>\n> ISTM that this shouldn't be needed in a test program like this?\n> Shouldn't libpq abstract all of this away?\n>\n\nFixed.\n\n>\n> > +static void\n> > +simple_batch(PGconn *conn)\n> > +{\n>\n> ISTM that all or at least several of these should include tests of\n> transactional behaviour with pipelining (e.g. using both implicit and\n> explicit transactions inside a single batch, using transactions across\n> batches, multiple explicit transactions inside a batch).\n>\n\n@Andres, just to make sure I understood, here is the test scenarios I'll add:\n\nImplicit and explicit multiple transactions:\n start batch:\n create_table\n insert X\n begin transaction\n insert X\n commit transaction\n begin transaction\n insert Y\n commit transaction\n end batch\n\nTransaction across batches:\n start batch:\n create_table\n begin transaction\n insert X\n end batch\n start batch:\n insert Y\n commit transaction\n end batch\n\n>\n>\n> > + PGresult *res = NULL;\n> > + const char *dummy_params[1] = {\"1\"};\n> > + Oid dummy_param_oids[1] = {INT4OID};\n> > +\n> > + fprintf(stderr, \"simple batch... \");\n> > + fflush(stderr);\n>\n> Why do we need fflush()? IMO that shouldn't be needed in a use like\n> this? Especially not on stderr, which ought to be unbuffered?\n>\nRemoved.\n\n>\n> > + /*\n> > + * Enter batch mode and dispatch a set of operations, which we'll then\n> > + * process the results of as they come in.\n> > + *\n> > + * For a simple case we should be able to do this without interim\n> > + * processing of results since our out buffer will give us enough slush to\n> > + * work with and we won't block on sending. So blocking mode is fine.\n> > + */\n> > + if (PQisnonblocking(conn))\n> > + {\n> > + fprintf(stderr, \"Expected blocking connection mode\\n\");\n> > + goto fail;\n> > + }\n>\n> Perhaps worth adding a helper for this?\n>\n> #define EXPECT(condition, explanation) \\\n>\n\nFixed (and saved 600 lines :).\n\n\n\nOnce I get your confirmation of the test scenarios, I'll implement\nthem and share another patch.", "msg_date": "Mon, 31 Aug 2020 18:05:47 +0200", "msg_from": "Matthieu Garrigues <matthieu.garrigues@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On 2020-Aug-31, Matthieu Garrigues wrote:\n\n> It seems like this patch is nearly finished. I fixed all the remaining\n> issues. I'm also asking a confirmation of the test scenarios you want\n> to see in the next version of the patch.\n\nHmm, apparently nobody noticed that this patch is not registered in the\ncurrent commitfest.\n\nSince it was submitted ahead of the deadline, I'm going to add it there.\n(The patch has also undergone a lot of review already; it's certainly\nnot a newcomer.)\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 4 Sep 2020 17:26:03 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "Alvaro,\n\n\nOn Fri, 4 Sep 2020 at 17:26, Alvaro Herrera <alvherre@2ndquadrant.com>\nwrote:\n\n> On 2020-Aug-31, Matthieu Garrigues wrote:\n>\n> > It seems like this patch is nearly finished. I fixed all the remaining\n> > issues. I'm also asking a confirmation of the test scenarios you want\n> > to see in the next version of the patch.\n>\n> Hmm, apparently nobody noticed that this patch is not registered in the\n> current commitfest.\n>\n> Since it was submitted ahead of the deadline, I'm going to add it there.\n> (The patch has also undergone a lot of review already; it's certainly\n> not a newcomer.)\n>\n\nI am looking for this in the commitfest and can't find it. However there is\nan old commitfest entry\n\nhttps://commitfest.postgresql.org/13/1024/\n\nDo you have the link for the new one ?\n\nDave Cramer\nwww.postgres.rocks\n\n\n>\n>\n>\n\nAlvaro,On Fri, 4 Sep 2020 at 17:26, Alvaro Herrera <alvherre@2ndquadrant.com> wrote:On 2020-Aug-31, Matthieu Garrigues wrote:\n\n> It seems like this patch is nearly finished. I fixed all the remaining\n> issues. I'm also asking a confirmation of the test scenarios you want\n> to see in the next version of the patch.\n\nHmm, apparently nobody noticed that this patch is not registered in the\ncurrent commitfest.\n\nSince it was submitted ahead of the deadline, I'm going to add it there.\n(The patch has also undergone a lot of review already; it's certainly\nnot a newcomer.)I am looking for this in the commitfest and can't find it. However there is an old commitfest entryhttps://commitfest.postgresql.org/13/1024/Do you have the link for the new one ?Dave Cramerwww.postgres.rocks", "msg_date": "Mon, 21 Sep 2020 08:38:07 -0400", "msg_from": "Dave Cramer <davecramer@postgres.rocks>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "Dave Cramer\nwww.postgres.rocks\n\n\nOn Mon, 31 Aug 2020 at 11:46, Matthieu Garrigues <\nmatthieu.garrigues@gmail.com> wrote:\n\n> Hi,\n>\n> It seems like this patch is nearly finished. I fixed all the remaining\n> issues. I'm also asking\n> a confirmation of the test scenarios you want to see in the next\n> version of the patch.\n>\n> > Hi,\n> >\n> > On 2020-07-10 19:01:49 -0400, Alvaro Herrera wrote:\n> > > Totally unasked for, here's a rebase of this patch series. I didn't do\n> > > anything other than rebasing to current master, solving a couple of\n> very\n> > > trivial conflicts, fixing some whitespace complaints by git apply, and\n> > > running tests to verify everthing works.\n> > >\n> > > I don't foresee working on this at all, so if anyone is interested in\n> > > seeing this feature in, I encourage them to read and address\n> > > Horiguchi-san's feedback.\n> >\n> > Nor am I planning to do so, but I do think its a pretty important\n> > improvement.\n> >\n> >\n> Fixed\n>\n> >\n> >\n> > > +/*\n> > > + * PQrecyclePipelinedCommand\n> > > + * Push a command queue entry onto the freelist. It must be a\n> dangling entry\n> > > + * with null next pointer and not referenced by any other entry's\n> next pointer.\n> > > + */\n> >\n> > Dangling sounds a bit like it's already freed.\n> >\n> >\n> Fixed\n>\n> >\n> >\n> > > +/*\n> > > + * PQbatchSendQueue\n> > > + * End a batch submission by sending a protocol sync. The connection\n> will\n> > > + * remain in batch mode and unavailable for new synchronous command\n> execution\n> > > + * functions until all results from the batch are processed by the\n> client.\n> >\n> > I feel like the reference to the protocol sync is a bit too low level\n> > for an external API. It should first document what the function does\n> > from a user's POV.\n> >\n> > I think it'd also be good to document whether / whether not queries can\n> > already have been sent before PQbatchSendQueue is called or not.\n> >\n> Fixed\n>\n> >\n> >\n> >\n> > > + if (conn->batch_status == PQBATCH_MODE_ABORTED && conn->queryclass\n> != PGQUERY_SYNC)\n> > > + {\n> > > + /*\n> > > + * In an aborted batch we don't get anything from the server for each\n> > > + * result; we're just discarding input until we get to the next sync\n> > > + * from the server. The client needs to know its queries got aborted\n> > > + * so we create a fake PGresult to return immediately from\n> > > + * PQgetResult.\n> > > + */\n> > > + conn->result = PQmakeEmptyPGresult(conn,\n> > > + PGRES_BATCH_ABORTED);\n> > > + if (!conn->result)\n> > > + {\n> > > + printfPQExpBuffer(&conn->errorMessage,\n> > > + libpq_gettext(\"out of memory\"));\n> > > + pqSaveErrorResult(conn);\n> > > + return 0;\n> >\n> > Is there any way an application can recover at this point? ISTM we'd be\n> > stuck in the previous asyncStatus, no?\n> >\n>\n> conn->result is null when malloc(sizeof(PGresult)) returns null. It's\n> very unlikely unless\n> the server machine is out of memory, so the server will probably be\n> unresponsive anyway.\n>\n> I'm leaving this as it is but if anyone has a solution simple to\n> implement I'll fix it.\n>\n> >\n> >\n> > > +/* pqBatchFlush\n> > > + * In batch mode, data will be flushed only when the out buffer\n> reaches the threshold value.\n> > > + * In non-batch mode, data will be flushed all the time.\n> > > + */\n> > > +static int\n> > > +pqBatchFlush(PGconn *conn)\n> > > +{\n> > > + if ((conn->batch_status == PQBATCH_MODE_OFF)||(conn->outCount >=\n> OUTBUFFER_THRESHOLD))\n> > > + return(pqFlush(conn));\n> > > + return 0; /* Just to keep compiler quiet */\n> > > +}\n> >\n> > unnecessarily long line.\n> >\n> Fixed\n>\n> >\n> > > +/*\n> > > + * Connection's outbuffer threshold is set to 64k as it is safe\n> > > + * in Windows as per comments in pqSendSome() API.\n> > > + */\n> > > +#define OUTBUFFER_THRESHOLD 65536\n> >\n> > I don't think the comment explains much. It's fine to send more than 64k\n> > with pqSendSome(), they'll just be send with separate pgsecure_write()\n> > invocations. And only on windows.\n> >\n> > It clearly makes sense to start sending out data at a certain\n> > granularity to avoid needing unnecessary amounts of memory, and to make\n> > more efficient use of latency / serer side compute.\n> >\n> > It's not implausible that 64k is the right amount for that, I just don't\n> > think the explanation above is good.\n> >\n>\n> Fixed\n>\n> > > diff --git a/src/test/modules/test_libpq/testlibpqbatch.c\n> b/src/test/modules/test_libpq/testlibpqbatch.c\n> > > new file mode 100644\n> > > index 0000000000..4d6ba266e5\n> > > --- /dev/null\n> > > +++ b/src/test/modules/test_libpq/testlibpqbatch.c\n> > > @@ -0,0 +1,1456 @@\n> > > +/*\n> > > + * src/test/modules/test_libpq/testlibpqbatch.c\n> > > + *\n> > > + *\n> > > + * testlibpqbatch.c\n> > > + * Test of batch execution functionality\n> > > + */\n> > > +\n> > > +#ifdef WIN32\n> > > +#include <windows.h>\n> > > +#endif\n> >\n> > ISTM that this shouldn't be needed in a test program like this?\n> > Shouldn't libpq abstract all of this away?\n> >\n>\n> Fixed.\n>\n> >\n> > > +static void\n> > > +simple_batch(PGconn *conn)\n> > > +{\n> >\n> > ISTM that all or at least several of these should include tests of\n> > transactional behaviour with pipelining (e.g. using both implicit and\n> > explicit transactions inside a single batch, using transactions across\n> > batches, multiple explicit transactions inside a batch).\n> >\n>\n> @Andres, just to make sure I understood, here is the test scenarios I'll\n> add:\n>\n> Implicit and explicit multiple transactions:\n> start batch:\n> create_table\n> insert X\n> begin transaction\n> insert X\n> commit transaction\n> begin transaction\n> insert Y\n> commit transaction\n> end batch\n>\n> Transaction across batches:\n> start batch:\n> create_table\n> begin transaction\n> insert X\n> end batch\n> start batch:\n> insert Y\n> commit transaction\n> end batch\n>\n> >\n> >\n> > > + PGresult *res = NULL;\n> > > + const char *dummy_params[1] = {\"1\"};\n> > > + Oid dummy_param_oids[1] = {INT4OID};\n> > > +\n> > > + fprintf(stderr, \"simple batch... \");\n> > > + fflush(stderr);\n> >\n> > Why do we need fflush()? IMO that shouldn't be needed in a use like\n> > this? Especially not on stderr, which ought to be unbuffered?\n> >\n> Removed.\n>\n> >\n> > > + /*\n> > > + * Enter batch mode and dispatch a set of operations, which we'll then\n> > > + * process the results of as they come in.\n> > > + *\n> > > + * For a simple case we should be able to do this without interim\n> > > + * processing of results since our out buffer will give us enough\n> slush to\n> > > + * work with and we won't block on sending. So blocking mode is fine.\n> > > + */\n> > > + if (PQisnonblocking(conn))\n> > > + {\n> > > + fprintf(stderr, \"Expected blocking connection mode\\n\");\n> > > + goto fail;\n> > > + }\n> >\n> > Perhaps worth adding a helper for this?\n> >\n> > #define EXPECT(condition, explanation) \\\n> >\n>\n> Fixed (and saved 600 lines :).\n>\n>\n>\n> Once I get your confirmation of the test scenarios, I'll implement\n> them and share another patch.\n>\n\n\nThere was a comment upthread a while back that people should look at the\ncomments made in\nhttps://www.postgresql.org/message-id/20180322.211148.187821341.horiguchi.kyotaro%40lab.ntt.co.jp\nby Horiguchi-San.\n\n From what I can tell this has not been addressed. The one big thing is the\nuse of PQbatchProcessQueue vs just putting it in PQgetResult.\n\nThe argument is that adding PQbatchProcessQueue is unnecessary and just\nadds another step. Looking at this, it seems like putting this inside\nPQgetResult would get my vote as it leaves the interface unchanged.\n\nDave\n\nDave Cramerwww.postgres.rocksOn Mon, 31 Aug 2020 at 11:46, Matthieu Garrigues <matthieu.garrigues@gmail.com> wrote:Hi,\n\nIt seems like this patch is nearly finished. I fixed all the remaining\nissues. I'm also asking\na confirmation of the test scenarios you want to see in the next\nversion of the patch.\n\n> Hi,\n>\n> On 2020-07-10 19:01:49 -0400, Alvaro Herrera wrote:\n> > Totally unasked for, here's a rebase of this patch series.  I didn't do\n> > anything other than rebasing to current master, solving a couple of very\n> > trivial conflicts, fixing some whitespace complaints by git apply, and\n> > running tests to verify everthing works.\n> >\n> > I don't foresee working on this at all, so if anyone is interested in\n> > seeing this feature in, I encourage them to read and address\n> > Horiguchi-san's feedback.\n>\n> Nor am I planning to do so, but I do think its a pretty important\n> improvement.\n>\n>\nFixed\n\n>\n>\n> > +/*\n> > + * PQrecyclePipelinedCommand\n> > + * Push a command queue entry onto the freelist. It must be a dangling entry\n> > + * with null next pointer and not referenced by any other entry's next pointer.\n> > + */\n>\n> Dangling sounds a bit like it's already freed.\n>\n>\nFixed\n\n>\n>\n> > +/*\n> > + * PQbatchSendQueue\n> > + * End a batch submission by sending a protocol sync. The connection will\n> > + * remain in batch mode and unavailable for new synchronous command execution\n> > + * functions until all results from the batch are processed by the client.\n>\n> I feel like the reference to the protocol sync is a bit too low level\n> for an external API. It should first document what the function does\n> from a user's POV.\n>\n> I think it'd also be good to document whether / whether not queries can\n> already have been sent before PQbatchSendQueue is called or not.\n>\nFixed\n\n>\n>\n>\n> > + if (conn->batch_status == PQBATCH_MODE_ABORTED && conn->queryclass != PGQUERY_SYNC)\n> > + {\n> > + /*\n> > + * In an aborted batch we don't get anything from the server for each\n> > + * result; we're just discarding input until we get to the next sync\n> > + * from the server. The client needs to know its queries got aborted\n> > + * so we create a fake PGresult to return immediately from\n> > + * PQgetResult.\n> > + */\n> > + conn->result = PQmakeEmptyPGresult(conn,\n> > +   PGRES_BATCH_ABORTED);\n> > + if (!conn->result)\n> > + {\n> > + printfPQExpBuffer(&conn->errorMessage,\n> > +  libpq_gettext(\"out of memory\"));\n> > + pqSaveErrorResult(conn);\n> > + return 0;\n>\n> Is there any way an application can recover at this point? ISTM we'd be\n> stuck in the previous asyncStatus, no?\n>\n\nconn->result is null when malloc(sizeof(PGresult)) returns null. It's\nvery unlikely unless\nthe server machine is out of memory, so the server will probably be\nunresponsive anyway.\n\nI'm leaving this as it is but if anyone has a solution simple to\nimplement I'll fix it.\n\n>\n>\n> > +/* pqBatchFlush\n> > + * In batch mode, data will be flushed only when the out buffer reaches the threshold value.\n> > + * In non-batch mode, data will be flushed all the time.\n> > + */\n> > +static int\n> > +pqBatchFlush(PGconn *conn)\n> > +{\n> > + if ((conn->batch_status == PQBATCH_MODE_OFF)||(conn->outCount >= OUTBUFFER_THRESHOLD))\n> > + return(pqFlush(conn));\n> > + return 0; /* Just to keep compiler quiet */\n> > +}\n>\n> unnecessarily long line.\n>\nFixed\n\n>\n> > +/*\n> > + * Connection's outbuffer threshold is set to 64k as it is safe\n> > + * in Windows as per comments in pqSendSome() API.\n> > + */\n> > +#define OUTBUFFER_THRESHOLD 65536\n>\n> I don't think the comment explains much. It's fine to send more than 64k\n> with pqSendSome(), they'll just be send with separate pgsecure_write()\n> invocations. And only on windows.\n>\n> It clearly makes sense to start sending out data at a certain\n> granularity to avoid needing unnecessary amounts of memory, and to make\n> more efficient use of latency / serer side compute.\n>\n> It's not implausible that 64k is the right amount for that, I just don't\n> think the explanation above is good.\n>\n\nFixed\n\n> > diff --git a/src/test/modules/test_libpq/testlibpqbatch.c b/src/test/modules/test_libpq/testlibpqbatch.c\n> > new file mode 100644\n> > index 0000000000..4d6ba266e5\n> > --- /dev/null\n> > +++ b/src/test/modules/test_libpq/testlibpqbatch.c\n> > @@ -0,0 +1,1456 @@\n> > +/*\n> > + * src/test/modules/test_libpq/testlibpqbatch.c\n> > + *\n> > + *\n> > + * testlibpqbatch.c\n> > + * Test of batch execution functionality\n> > + */\n> > +\n> > +#ifdef WIN32\n> > +#include <windows.h>\n> > +#endif\n>\n> ISTM that this shouldn't be needed in a test program like this?\n> Shouldn't libpq abstract all of this away?\n>\n\nFixed.\n\n>\n> > +static void\n> > +simple_batch(PGconn *conn)\n> > +{\n>\n> ISTM that all or at least several of these should include tests of\n> transactional behaviour with pipelining (e.g. using both implicit and\n> explicit transactions inside a single batch, using transactions across\n> batches, multiple explicit transactions inside a batch).\n>\n\n@Andres, just to make sure I understood, here is the test scenarios I'll add:\n\nImplicit and explicit multiple transactions:\n   start batch:\n     create_table\n     insert X\n     begin transaction\n       insert X\n     commit transaction\n     begin transaction\n       insert Y\n     commit transaction\n  end batch\n\nTransaction across batches:\n   start batch:\n     create_table\n     begin transaction\n       insert X\n   end batch\n   start batch:\n       insert Y\n    commit transaction\n  end batch\n\n>\n>\n> > + PGresult   *res = NULL;\n> > + const char *dummy_params[1] = {\"1\"};\n> > + Oid dummy_param_oids[1] = {INT4OID};\n> > +\n> > + fprintf(stderr, \"simple batch... \");\n> > + fflush(stderr);\n>\n> Why do we need fflush()? IMO that shouldn't be needed in a use like\n> this? Especially not on stderr, which ought to be unbuffered?\n>\nRemoved.\n\n>\n> > + /*\n> > + * Enter batch mode and dispatch a set of operations, which we'll then\n> > + * process the results of as they come in.\n> > + *\n> > + * For a simple case we should be able to do this without interim\n> > + * processing of results since our out buffer will give us enough slush to\n> > + * work with and we won't block on sending. So blocking mode is fine.\n> > + */\n> > + if (PQisnonblocking(conn))\n> > + {\n> > + fprintf(stderr, \"Expected blocking connection mode\\n\");\n> > + goto fail;\n> > + }\n>\n> Perhaps worth adding a helper for this?\n>\n> #define EXPECT(condition, explanation) \\\n>\n\nFixed (and saved 600 lines :).\n\n\n\nOnce I get your confirmation of the test scenarios, I'll implement\nthem and share another patch.There was a comment upthread a while back that people should look at the comments made in https://www.postgresql.org/message-id/20180322.211148.187821341.horiguchi.kyotaro%40lab.ntt.co.jp by Horiguchi-San. From what I can tell this has not been addressed. The one big thing is the use of PQbatchProcessQueue vs just putting it in PQgetResult.The argument is that adding PQbatchProcessQueue is unnecessary and just adds another step. Looking at this, it seems like putting this inside PQgetResult would get my vote as it leaves the interface unchanged.Dave", "msg_date": "Mon, 21 Sep 2020 09:08:49 -0400", "msg_from": "Dave Cramer <davecramer@postgres.rocks>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On 2020-Sep-21, Dave Cramer wrote:\n\nHello Dave,\n\n> I am looking for this in the commitfest and can't find it. However there is\n> an old commitfest entry\n> \n> https://commitfest.postgresql.org/13/1024/\n> \n> Do you have the link for the new one ?\n\nHere you go:\n\nhttps://commitfest.postgresql.org/29/2724/\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 21 Sep 2020 10:21:11 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On Mon, 21 Sep 2020 at 09:21, Matthieu Garrigues <\nmatthieu.garrigues@gmail.com> wrote:\n\n> Matthieu Garrigues\n>\n> On Mon, Sep 21, 2020 at 3:09 PM Dave Cramer <davecramer@postgres.rocks>\n> wrote:\n> >>\n> > There was a comment upthread a while back that people should look at the\n> comments made in\n> https://www.postgresql.org/message-id/20180322.211148.187821341.horiguchi.kyotaro%40lab.ntt.co.jp\n> by Horiguchi-San.\n> >\n> > From what I can tell this has not been addressed. The one big thing is\n> the use of PQbatchProcessQueue vs just putting it in PQgetResult.\n> >\n> > The argument is that adding PQbatchProcessQueue is unnecessary and just\n> adds another step. Looking at this, it seems like putting this inside\n> PQgetResult would get my vote as it leaves the interface unchanged.\n> >\n>\n> Ok. I'll merge PQbatchProcessQueue into PQgetResult. But just one\n> thing: I'll keep PQgetResult returning null between the result of two\n> batched query so the user\n> can know which result comes from which query.\n>\n\nFair enough.\n\nThere may be other things in his comments that need to be addressed. That\nwas the big one that stuck out for me.\n\nThanks for working on this!\n\n\nDave Cramer\nwww.postgres.rocks\n\nOn Mon, 21 Sep 2020 at 09:21, Matthieu Garrigues <matthieu.garrigues@gmail.com> wrote:Matthieu Garrigues\n\nOn Mon, Sep 21, 2020 at 3:09 PM Dave Cramer <davecramer@postgres.rocks> wrote:\n>>\n> There was a comment upthread a while back that people should look at the comments made in https://www.postgresql.org/message-id/20180322.211148.187821341.horiguchi.kyotaro%40lab.ntt.co.jp by Horiguchi-San.\n>\n> From what I can tell this has not been addressed. The one big thing is the use of PQbatchProcessQueue vs just putting it in PQgetResult.\n>\n> The argument is that adding PQbatchProcessQueue is unnecessary and just adds another step. Looking at this, it seems like putting this inside PQgetResult would get my vote as it leaves the interface unchanged.\n>\n\nOk. I'll merge PQbatchProcessQueue into PQgetResult. But just one\nthing: I'll keep PQgetResult returning null between the result of two\nbatched query so the user\ncan know which result comes from which query.Fair enough.There may be other things in his comments that need to be addressed. That was the big one that stuck out for me.Thanks for working on this!Dave Cramerwww.postgres.rocks", "msg_date": "Mon, 21 Sep 2020 09:39:23 -0400", "msg_from": "Dave Cramer <davecramer@postgres.rocks>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "Matthieu Garrigues\n\nOn Mon, Sep 21, 2020 at 3:09 PM Dave Cramer <davecramer@postgres.rocks> wrote:\n>>\n> There was a comment upthread a while back that people should look at the comments made in https://www.postgresql.org/message-id/20180322.211148.187821341.horiguchi.kyotaro%40lab.ntt.co.jp by Horiguchi-San.\n>\n> From what I can tell this has not been addressed. The one big thing is the use of PQbatchProcessQueue vs just putting it in PQgetResult.\n>\n> The argument is that adding PQbatchProcessQueue is unnecessary and just adds another step. Looking at this, it seems like putting this inside PQgetResult would get my vote as it leaves the interface unchanged.\n>\n\nOk. I'll merge PQbatchProcessQueue into PQgetResult. But just one\nthing: I'll keep PQgetResult returning null between the result of two\nbatched query so the user\ncan know which result comes from which query.\n\n\n", "msg_date": "Mon, 21 Sep 2020 15:41:13 +0200", "msg_from": "Matthieu Garrigues <matthieu.garrigues@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On Mon, Sep 21, 2020 at 3:39 PM Dave Cramer <davecramer@postgres.rocks> wrote:\n>\n>\n>\n> On Mon, 21 Sep 2020 at 09:21, Matthieu Garrigues <matthieu.garrigues@gmail.com> wrote:\n>>\n>> Matthieu Garrigues\n>>\n>> On Mon, Sep 21, 2020 at 3:09 PM Dave Cramer <davecramer@postgres.rocks> wrote:\n>> >>\n>> > There was a comment upthread a while back that people should look at the comments made in https://www.postgresql.org/message-id/20180322.211148.187821341.horiguchi.kyotaro%40lab.ntt.co.jp by Horiguchi-San.\n>> >\n>> > From what I can tell this has not been addressed. The one big thing is the use of PQbatchProcessQueue vs just putting it in PQgetResult.\n>> >\n>> > The argument is that adding PQbatchProcessQueue is unnecessary and just adds another step. Looking at this, it seems like putting this inside PQgetResult would get my vote as it leaves the interface unchanged.\n>> >\n>>\n>> Ok. I'll merge PQbatchProcessQueue into PQgetResult. But just one\n>> thing: I'll keep PQgetResult returning null between the result of two\n>> batched query so the user\n>> can know which result comes from which query.\n>\n>\n> Fair enough.\n>\n> There may be other things in his comments that need to be addressed. That was the big one that stuck out for me.\n>\n> Thanks for working on this!\n>\n\nYes I already addressed the other things in the v19 patch:\nhttps://www.postgresql.org/message-id/flat/CAJkzx4T5E-2cQe3dtv2R78dYFvz+in8PY7A8MArvLhs_pg75gg@mail.gmail.com\n\n\n", "msg_date": "Mon, 21 Sep 2020 16:22:51 +0200", "msg_from": "Matthieu Garrigues <matthieu.garrigues@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "Hi Dave,\nI merged PQbatchProcessQueue into PQgetResult.\nOne first init call to PQbatchProcessQueue was also required in\nPQsendQueue to have\nPQgetResult ready to read the first batch query.\n\nTests and documentation are updated accordingly.\n\nMatthieu Garrigues\n\nOn Mon, Sep 21, 2020 at 3:39 PM Dave Cramer <davecramer@postgres.rocks> wrote:\n>\n>\n>\n> On Mon, 21 Sep 2020 at 09:21, Matthieu Garrigues <matthieu.garrigues@gmail.com> wrote:\n>>\n>> Matthieu Garrigues\n>>\n>> On Mon, Sep 21, 2020 at 3:09 PM Dave Cramer <davecramer@postgres.rocks> wrote:\n>> >>\n>> > There was a comment upthread a while back that people should look at the comments made in https://www.postgresql.org/message-id/20180322.211148.187821341.horiguchi.kyotaro%40lab.ntt.co.jp by Horiguchi-San.\n>> >\n>> > From what I can tell this has not been addressed. The one big thing is the use of PQbatchProcessQueue vs just putting it in PQgetResult.\n>> >\n>> > The argument is that adding PQbatchProcessQueue is unnecessary and just adds another step. Looking at this, it seems like putting this inside PQgetResult would get my vote as it leaves the interface unchanged.\n>> >\n>>\n>> Ok. I'll merge PQbatchProcessQueue into PQgetResult. But just one\n>> thing: I'll keep PQgetResult returning null between the result of two\n>> batched query so the user\n>> can know which result comes from which query.\n>\n>\n> Fair enough.\n>\n> There may be other things in his comments that need to be addressed. That was the big one that stuck out for me.\n>\n> Thanks for working on this!\n>\n>\n> Dave Cramer\n> www.postgres.rocks", "msg_date": "Mon, 21 Sep 2020 19:55:03 +0200", "msg_from": "Matthieu Garrigues <matthieu.garrigues@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On Mon, Sep 21, 2020 at 07:55:03PM +0200, Matthieu Garrigues wrote:\n> I merged PQbatchProcessQueue into PQgetResult.\n> One first init call to PQbatchProcessQueue was also required in\n> PQsendQueue to have\n> PQgetResult ready to read the first batch query.\n> \n> Tests and documentation are updated accordingly.\n\nThe documentation is failing to build, and the patch does not build\ncorrectly on Windows. Could you address that?\n--\nMichael", "msg_date": "Thu, 1 Oct 2020 13:35:21 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On Thu, Oct 1, 2020 at 6:35 AM Michael Paquier <michael@paquier.xyz> wrote:\n\n> The documentation is failing to build, and the patch does not build\n> correctly on Windows. Could you address that?\n> --\n> Michael\n\nYes I'm on it.\n\n-- \nMatthieu\n\n\n", "msg_date": "Thu, 1 Oct 2020 08:41:27 +0200", "msg_from": "Matthieu Garrigues <matthieu.garrigues@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "This patch fixes compilation on windows and compilation of the documentation.\n\nMatthieu Garrigues\n\nOn Thu, Oct 1, 2020 at 8:41 AM Matthieu Garrigues\n<matthieu.garrigues@gmail.com> wrote:\n>\n> On Thu, Oct 1, 2020 at 6:35 AM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> > The documentation is failing to build, and the patch does not build\n> > correctly on Windows. Could you address that?\n> > --\n> > Michael\n>\n> Yes I'm on it.\n>\n> --\n> Matthieu", "msg_date": "Thu, 1 Oct 2020 10:13:44 +0200", "msg_from": "Matthieu Garrigues <matthieu.garrigues@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "I started reading this patch. As a starting point I decided to post an\nupdated copy (v22), wherein I reverted the overwriting of\nsrc/include/port/linux.h with the win32.h contents (?) and the inclusion\nof <windows.h> in libpq-fe.h. If those are needed, some different\nsolution will have to be found.\n\nTrivial other changes (pgindent etc); nothing of substance. With the\nPQtrace() patch I posted at [1] the added test program crashes -- I\ndon't know if the fault lies in this patch or the other one.\n\n[1] https://postgr.es/m/20201026162313.GA22502@alvherre.pgsql", "msg_date": "Mon, 26 Oct 2020 16:09:36 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "In v23 I've gone over docs; discovered that PQgetResults docs were\nmissing the new values. Added those. No significant other changes yet.\n\n\n\n", "msg_date": "Mon, 2 Nov 2020 12:45:25 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On 2020-Nov-02, Alvaro Herrera wrote:\n\n> In v23 I've gone over docs; discovered that PQgetResults docs were\n> missing the new values. Added those. No significant other changes yet.", "msg_date": "Mon, 2 Nov 2020 12:57:52 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "Alvaro,\n\n\nOn Mon, 2 Nov 2020 at 10:57, Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n\n> On 2020-Nov-02, Alvaro Herrera wrote:\n>\n> > In v23 I've gone over docs; discovered that PQgetResults docs were\n> > missing the new values. Added those. No significant other changes yet.\n>\n>\n>\nThanks for looking at this.\n\nWhat else does it need to get it in shape to apply?\n\n\nDave Cramer\nwww.postgres.rocks\n\nAlvaro,On Mon, 2 Nov 2020 at 10:57, Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:On 2020-Nov-02, Alvaro Herrera wrote:\n\n> In v23 I've gone over docs; discovered that PQgetResults docs were\n> missing the new values.  Added those.  No significant other changes yet.\n\nThanks for looking at this.What else does it need to get it in shape to apply?Dave Cramerwww.postgres.rocks", "msg_date": "Tue, 3 Nov 2020 08:20:03 -0500", "msg_from": "Dave Cramer <davecramer@postgres.rocks>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "Hi Dave,\n\nOn 2020-Nov-03, Dave Cramer wrote:\n\n> On Mon, 2 Nov 2020 at 10:57, Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> \n> > On 2020-Nov-02, Alvaro Herrera wrote:\n> >\n> > > In v23 I've gone over docs; discovered that PQgetResults docs were\n> > > missing the new values. Added those. No significant other changes yet.\n>\n> Thanks for looking at this.\n> \n> What else does it need to get it in shape to apply?\n\nI want to go over the code in depth to grok the design more fully.\n\nIt would definitely help if you (and others) could think about the API\nbeing added: Does it fulfill the promises being made? Does it offer the\nguarantees that real-world apps want to have? I'm not much of an\napplication writer myself -- particularly high-traffic apps that would\nwant to use this. As a driver author I would welcome your insight in\nthese questions.\n\n\n\n", "msg_date": "Tue, 3 Nov 2020 10:42:34 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On Tue, 3 Nov 2020 at 08:42, Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n\n> Hi Dave,\n>\n> On 2020-Nov-03, Dave Cramer wrote:\n>\n> > On Mon, 2 Nov 2020 at 10:57, Alvaro Herrera <alvherre@alvh.no-ip.org>\n> wrote:\n> >\n> > > On 2020-Nov-02, Alvaro Herrera wrote:\n> > >\n> > > > In v23 I've gone over docs; discovered that PQgetResults docs were\n> > > > missing the new values. Added those. No significant other changes\n> yet.\n> >\n> > Thanks for looking at this.\n> >\n> > What else does it need to get it in shape to apply?\n>\n> I want to go over the code in depth to grok the design more fully.\n>\n> It would definitely help if you (and others) could think about the API\n> being added: Does it fulfill the promises being made? Does it offer the\n> guarantees that real-world apps want to have? I'm not much of an\n> application writer myself -- particularly high-traffic apps that would\n> want to use this. As a driver author I would welcome your insight in\n> these questions.\n>\n>\nI'm sort of in the same boat as you. While I'm closer to the client. I\ndon't personally write that much client code.\n\nI'd really like to hear from the users here.\n\n\nDave Cramer\nwww.postgres.rocks\n\nOn Tue, 3 Nov 2020 at 08:42, Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:Hi Dave,\n\nOn 2020-Nov-03, Dave Cramer wrote:\n\n> On Mon, 2 Nov 2020 at 10:57, Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> \n> > On 2020-Nov-02, Alvaro Herrera wrote:\n> >\n> > > In v23 I've gone over docs; discovered that PQgetResults docs were\n> > > missing the new values.  Added those.  No significant other changes yet.\n>\n> Thanks for looking at this.\n> \n> What else does it need to get it in shape to apply?\n\nI want to go over the code in depth to grok the design more fully.\n\nIt would definitely help if you (and others) could think about the API\nbeing added: Does it fulfill the promises being made?  Does it offer the\nguarantees that real-world apps want to have?  I'm not much of an\napplication writer myself -- particularly high-traffic apps that would\nwant to use this.  As a driver author I would welcome your insight in\nthese questions.\nI'm sort of in the same boat as you. While I'm closer to the client. I don't personally write that much client code.I'd really like to hear from the users here.Dave Cramerwww.postgres.rocks", "msg_date": "Tue, 3 Nov 2020 10:56:31 -0500", "msg_from": "Dave Cramer <davecramer@postgres.rocks>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "I implemented a C++ async HTTP server using this new batch mode and it\nprovides everything I needed to transparently batch sql requests.\nIt gives a performance boost between x2 and x3 on this benchmark:\nhttps://www.techempower.com/benchmarks/#section=test&runid=3097dbae-5228-454c-ba2e-2055d3982790&hw=ph&test=query&a=2&f=zik0zj-zik0zj-zik0zj-zik0zj-zieepr-zik0zj-zik0zj-zik0zj-zik0zj-zik0zj-zik0zj\n\nI'll ask other users interested in this to review the API.\n\nMatthieu Garrigues\n\nOn Tue, Nov 3, 2020 at 4:56 PM Dave Cramer <davecramer@postgres.rocks> wrote:\n>\n>\n>\n> On Tue, 3 Nov 2020 at 08:42, Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n>>\n>> Hi Dave,\n>>\n>> On 2020-Nov-03, Dave Cramer wrote:\n>>\n>> > On Mon, 2 Nov 2020 at 10:57, Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n>> >\n>> > > On 2020-Nov-02, Alvaro Herrera wrote:\n>> > >\n>> > > > In v23 I've gone over docs; discovered that PQgetResults docs were\n>> > > > missing the new values. Added those. No significant other changes yet.\n>> >\n>> > Thanks for looking at this.\n>> >\n>> > What else does it need to get it in shape to apply?\n>>\n>> I want to go over the code in depth to grok the design more fully.\n>>\n>> It would definitely help if you (and others) could think about the API\n>> being added: Does it fulfill the promises being made? Does it offer the\n>> guarantees that real-world apps want to have? I'm not much of an\n>> application writer myself -- particularly high-traffic apps that would\n>> want to use this. As a driver author I would welcome your insight in\n>> these questions.\n>>\n>\n> I'm sort of in the same boat as you. While I'm closer to the client. I don't personally write that much client code.\n>\n> I'd really like to hear from the users here.\n>\n>\n> Dave Cramer\n> www.postgres.rocks\n\n\n", "msg_date": "Tue, 3 Nov 2020 17:44:59 +0100", "msg_from": "Matthieu Garrigues <matthieu.garrigues@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On Mon, Nov 2, 2020 at 8:58 AM Alvaro Herrera <alvherre@alvh.no-ip.org>\nwrote:\n\n> On 2020-Nov-02, Alvaro Herrera wrote:\n>\n> > In v23 I've gone over docs; discovered that PQgetResults docs were\n> > missing the new values. Added those. No significant other changes yet.\n>\n>\nJust reading the documentation of this patch, haven't been following the\nlonger thread:\n\nGiven the caveats around blocking mode connections why not just require\nnon-blocking mode, in a similar fashion to how synchronous functions are\ndisallowed?\n\n\"Batched operations will be executed by the server in the order the client\nsends them. The server will send the results in the order the statements\nexecuted.\"\n\nMaybe:\n\n\"The server executes statements, and returns results, in the order the\nclient sends them.\"\n\nUsing two sentences and relying on the user to mentally link the two \"in\nthe order\" descriptions together seems to add unnecessary cognitive load.\n\n+ The client <link linkend=\"libpq-batch-interleave\">interleaves result\n+ processing</link> with sending batch queries, or for small batches may\n+ process all results after sending the whole batch.\n\nSuggest: \"The client may choose to interleave result processing with\nsending batch queries, or wait until the complete batch has been sent.\"\n\nI would expect to process the results of a batch only after sending the\nentire batch to the server. That I don't have to is informative but\nknowing when I should avoid doing so, and why, is informative as well. To\nthe extreme while you can use batch mode and interleave if you just poll\ngetResult after every command you will make the whole batch thing\npointless. Directing the reader from here to the section \"Interleaving\nResult Processing and Query Dispatch\" seems worth considering. The\ndynamics of small sizes and sockets remains a bit unclear as to what will\nbreak (if anything, or is it just process memory on the server) if\ninterleaving it not performed and sizes are large.\n\nI would suggest placing commentary about \"all transactions subsequent to a\nfailed transaction in a batch are ignored while previous completed\ntransactions are retained\" in the \"When to Use Batching\". Something like\n\"Batching is less useful, and more complex, when a single batch contains\nmultiple transactions (see Error Handling).\"\n\nMy imagined use case would be to open a batch, start a transaction, send\nall of its components, end the transaction, end the batch, check for batch\nfailure and if it doesn't fail have the option to easily continue without\nprocessing individual pgResults (or if it does fail, have the option to\nextract the first error pgResult and continue, ignoring the rest, knowing\nthat the transaction as a whole was reverted and the batch unapplied).\nI've never interfaced with libpq directly. Though given how the existing C\nAPI works what is implemented here seems consistent.\n\nThe \"queueing up queries into a pipeline to be executed as a batch on the\nserver\" can be read as a client-side behavior where nothing is sent to the\nserver until the batch has been completed. Reading further it becomes\nclear that all it basically is is a sever-side toggle that instructs the\nserver to continue processing incoming commands even while prior commands\nhave their results waiting to be ingested by the client.\n\nBatch seems like the user-visible term to describe this feature. Pipeline\nseems like an implementation detail that doesn't need to be mentioned in\nthe documentation - especially given that pipeline doesn't get a mentioned\nbeyond the first two paragraphs of the chapter and never without being\nlinked directly to \"batch\". I would probably leave the indexterm and have\na paragraph describing that batching is implemented using a query pipeline\nso that people with the implementation detail on their mind can find this\nchapter, but the prose for the user should just stick to batching.\n\nSorry, that all is a bit unfocused, but the documentation for the user of\nthe API could be cleaned up a bit and some more words spent on\nwhat trade-offs are being made when using batching versus normal\ncommand-response processing. That said, while I don't see all of this\npurely a matter of style I'm also not seeing anything demonstrably wrong\nwith the documentation at the moment. Hopefully my perspective helps\nthough, and depending on what happens next I may try and make my thoughts\nmore concrete with an actual patch.\n\nDavid J.\n\nOn Mon, Nov 2, 2020 at 8:58 AM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:On 2020-Nov-02, Alvaro Herrera wrote:\n\n> In v23 I've gone over docs; discovered that PQgetResults docs were\n> missing the new values.  Added those.  No significant other changes yet.Just reading the documentation of this patch, haven't been following the longer thread:Given the caveats around blocking mode connections why not just require non-blocking mode, in a similar fashion to how synchronous functions are disallowed?\"Batched operations will be executed by the server in the order the clientsends them. The server will send the results in the order the statementsexecuted.\"Maybe:\"The server executes statements, and returns results, in the order the client sends them.\"Using two sentences and relying on the user to mentally link the two \"in the order\" descriptions together seems to add unnecessary cognitive load.+     The client <link linkend=\"libpq-batch-interleave\">interleaves result+     processing</link> with sending batch queries, or for small batches may+     process all results after sending the whole batch.Suggest: \"The client may choose to interleave result processing with sending batch queries, or wait until the complete batch has been sent.\"I would expect to process the results of a batch only after sending the entire batch to the server.  That I don't have to is informative but knowing when I should avoid doing so, and why, is informative as well.  To the extreme while you can use batch mode and interleave if you just poll getResult after every command you will make the whole batch thing pointless.  Directing the reader from here to the section \"Interleaving Result Processing and Query Dispatch\" seems worth considering.  The dynamics of small sizes and sockets remains a bit unclear as to what will break (if anything, or is it just process memory on the server) if interleaving it not performed and sizes are large.I would suggest placing commentary about \"all transactions subsequent to a failed transaction in a batch are ignored while previous completed transactions are retained\" in the \"When to Use Batching\".  Something like \"Batching is less useful, and more complex, when a single batch contains multiple transactions (see Error Handling).\"My imagined use case would be to open a batch, start a transaction, send all of its components, end the transaction, end the batch, check for batch failure and if it doesn't fail have the option to easily continue without processing individual pgResults (or if it does fail, have the option to extract the first error pgResult and continue, ignoring the rest, knowing that the transaction as a whole was reverted and the batch unapplied).  I've never interfaced with libpq directly.  Though given how the existing C API works what is implemented here seems consistent.The \"queueing up queries into a pipeline to be executed as a batch on the server\" can be read as a client-side behavior where nothing is sent to the server until the batch has been completed.  Reading further it becomes clear that all it basically is is a sever-side toggle that instructs the server to continue processing incoming commands even while prior commands have their results waiting to be ingested by the client.Batch seems like the user-visible term to describe this feature.  Pipeline seems like an implementation detail that doesn't need to be mentioned in the documentation - especially given that pipeline doesn't get a mentioned beyond the first two paragraphs of the chapter and never without being linked directly to \"batch\".  I would probably leave the indexterm and have a paragraph describing that batching is implemented using a query pipeline so that people with the implementation detail on their mind can find this chapter, but the prose for the user should just stick to batching.Sorry, that all is a bit unfocused, but the documentation for the user of the API could be cleaned up a bit and some more words spent on what trade-offs are being made when using batching versus normal command-response processing.  That said, while I don't see all of this purely a matter of style I'm also not seeing anything demonstrably wrong with the documentation at the moment.  Hopefully my perspective helps though, and depending on what happens next I may try and make my thoughts more concrete with an actual patch.David J.", "msg_date": "Tue, 3 Nov 2020 10:20:53 -0700", "msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "Hi,\n\nOn 2020-11-03 10:42:34 -0300, Alvaro Herrera wrote:\n> It would definitely help if you (and others) could think about the API\n> being added: Does it fulfill the promises being made? Does it offer the\n> guarantees that real-world apps want to have? I'm not much of an\n> application writer myself -- particularly high-traffic apps that would\n> want to use this.\n\nSomewhere earlier in this thread there was a patch with support for\nbatching in pgbench. I think it'd be good to refresh that. Both because\nit shows at least some real-world-lite usage of the feature and because\nwe need a way to stress it to see whether it has unnecessary\nbottlenecks.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 11 Nov 2020 14:46:30 -0800", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "Hi David,\n\nThanks for the feedback. I did rework a bit the doc based on your\nremarks. Here is the v24 patch.\n\nMatthieu Garrigues\n\nOn Tue, Nov 3, 2020 at 6:21 PM David G. Johnston\n<david.g.johnston@gmail.com> wrote:\n>\n> On Mon, Nov 2, 2020 at 8:58 AM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n>>\n>> On 2020-Nov-02, Alvaro Herrera wrote:\n>>\n>> > In v23 I've gone over docs; discovered that PQgetResults docs were\n>> > missing the new values. Added those. No significant other changes yet.\n>>\n>\n> Just reading the documentation of this patch, haven't been following the longer thread:\n>\n> Given the caveats around blocking mode connections why not just require non-blocking mode, in a similar fashion to how synchronous functions are disallowed?\n>\n> \"Batched operations will be executed by the server in the order the client\n> sends them. The server will send the results in the order the statements\n> executed.\"\n>\n> Maybe:\n>\n> \"The server executes statements, and returns results, in the order the client sends them.\"\n>\n> Using two sentences and relying on the user to mentally link the two \"in the order\" descriptions together seems to add unnecessary cognitive load.\n>\n> + The client <link linkend=\"libpq-batch-interleave\">interleaves result\n> + processing</link> with sending batch queries, or for small batches may\n> + process all results after sending the whole batch.\n>\n> Suggest: \"The client may choose to interleave result processing with sending batch queries, or wait until the complete batch has been sent.\"\n>\n> I would expect to process the results of a batch only after sending the entire batch to the server. That I don't have to is informative but knowing when I should avoid doing so, and why, is informative as well. To the extreme while you can use batch mode and interleave if you just poll getResult after every command you will make the whole batch thing pointless. Directing the reader from here to the section \"Interleaving Result Processing and Query Dispatch\" seems worth considering. The dynamics of small sizes and sockets remains a bit unclear as to what will break (if anything, or is it just process memory on the server) if interleaving it not performed and sizes are large.\n>\n> I would suggest placing commentary about \"all transactions subsequent to a failed transaction in a batch are ignored while previous completed transactions are retained\" in the \"When to Use Batching\". Something like \"Batching is less useful, and more complex, when a single batch contains multiple transactions (see Error Handling).\"\n>\n> My imagined use case would be to open a batch, start a transaction, send all of its components, end the transaction, end the batch, check for batch failure and if it doesn't fail have the option to easily continue without processing individual pgResults (or if it does fail, have the option to extract the first error pgResult and continue, ignoring the rest, knowing that the transaction as a whole was reverted and the batch unapplied). I've never interfaced with libpq directly. Though given how the existing C API works what is implemented here seems consistent.\n>\n> The \"queueing up queries into a pipeline to be executed as a batch on the server\" can be read as a client-side behavior where nothing is sent to the server until the batch has been completed. Reading further it becomes clear that all it basically is is a sever-side toggle that instructs the server to continue processing incoming commands even while prior commands have their results waiting to be ingested by the client.\n>\n> Batch seems like the user-visible term to describe this feature. Pipeline seems like an implementation detail that doesn't need to be mentioned in the documentation - especially given that pipeline doesn't get a mentioned beyond the first two paragraphs of the chapter and never without being linked directly to \"batch\". I would probably leave the indexterm and have a paragraph describing that batching is implemented using a query pipeline so that people with the implementation detail on their mind can find this chapter, but the prose for the user should just stick to batching.\n>\n> Sorry, that all is a bit unfocused, but the documentation for the user of the API could be cleaned up a bit and some more words spent on what trade-offs are being made when using batching versus normal command-response processing. That said, while I don't see all of this purely a matter of style I'm also not seeing anything demonstrably wrong with the documentation at the moment. Hopefully my perspective helps though, and depending on what happens next I may try and make my thoughts more concrete with an actual patch.\n>\n> David J.\n>", "msg_date": "Thu, 12 Nov 2020 10:46:54 +0100", "msg_from": "Matthieu Garrigues <matthieu.garrigues@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "(Adding previous reviewers to CC)\n\nOn 2020-Nov-03, David G. Johnston wrote:\n\n> Given the caveats around blocking mode connections why not just require\n> non-blocking mode, in a similar fashion to how synchronous functions are\n> disallowed?\n\nThis is a very good question. Why indeed? Does anybody have a good\nanswer to this? If not, I propose we just require that non-blocking\nmode is in use in order for batch mode to be used.\n\nI've been doing a review pass over this patch and have an updated\nversion, which I intend to share later today (after I fix what appears\nto be a misunderstanding in the \"singlerow\" test in testlibpqbatch.c)\n\n\n", "msg_date": "Thu, 12 Nov 2020 10:40:43 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "Here's a v25.\n\nI made a few more changes to the docs per David's suggestions; I also\nreordered the sections quite a bit. It's now like this:\n * Batch Mode\n * Using Batch Mode\n * Issuing Queries\n * Processing Results\n * Error Handling\n * Interleaving Result Processing and Query Dispatch\n * Ending Batch Mode\n * Functions Associated with Batch Mode\n * When to Use Batching\n\nTo me as a reader, this makes more sense, but if you disagree, I think\nwe should discuss further changes. (For example, maybe we should move\nthe \"Functions\" section at the end?) The original had \"When to Use\nBatching\" at the start, but it seemed to me that the points it's making\nare not as critical as understanding what it is.\n\nI reworked the test program to better fit the TAP model; I found that if\none test mecha failed in whatever way, the connection would be in a\nweird state and cause the next test to also fail. I changed so that it\nruns one test and exits; then the t/001_libpq_async.pl file (hmm, need\nto rename to 001_batch.pl I guess) calls it once for each test.\nI adapted the test code to our code style. I also removed the \"timings\"\nstuff; I think that's something better left to pgbench.\n\n(I haven't looked at Daniel's pgbench stuff yet, but I will do that\nnext.)\n\nWhile looking at how the tests worked, I gave a hard stare at the new\nlibpq code and cleaned it up also. There's a lot of minor changes, but\nnothing truly substantial. I moved the code around a lot, to keep\nthings where grouped together they belong.\n\nI'm not 100% clear on things like PGconn->batch_status and how\nPGconn->asyncStatus works. Currently everything seems to work\ncorrectly, but I'm worried that because we add new status values to\nasyncStatus, some existing code might not be doing everything correctly\n(for example when changing to/from ASYNC_BUSY in some cases, are we 100%\nwe shouldn't be changing to ASYNC_QUEUED?)\n\n\nWhile looking this over I noticed a thread from 2014[1] where Matt\nNewell tried to implement this stuff and apparently the main review\ncomment he got before abandoning the patch was that the user would like\na way to access the query that corresponded to each result. The current\npatch set does not address that need; the approach to this problem is\nthat it's on the application's head to keep track of this. Honestly I\ndon't understand why it would be otherwise ... I'm not sure that it\nmakes sense to expect that the application is stupid enough that it\ndoesn't keep track in which order it sent things, but bright enough to\nkeep pointers to the queries it sent (??). So this seems okay to me.\nBut added Heikki and Claudio to CC because of that old thread.\n\n\n[1] https://postgr.es/m/2059418.jZQvL3lH90@obsidian", "msg_date": "Fri, 13 Nov 2020 21:37:53 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "\tAlvaro Herrera wrote:\n\n> I adapted the test code to our code style. I also removed the \"timings\"\n> stuff; I think that's something better left to pgbench.\n> \n> (I haven't looked at Daniel's pgbench stuff yet, but I will do that\n> next.)\n\nThe patch I posted in [1] was pretty simple, but at the time, query\nresults were always discarded. Now that pgbench can instantiate\nvariables from query results, a script can do:\n select 1 as var \\gset\n select :var;\nThis kind of sequence wouldn't work in batch mode since it\nsends queries before getting results of previous queries.\n\nSo maybe \\gset should be rejected when inside a batch section.\n\nOr alternatively pgbench should collect results before a variable is\nreinjected into a query, thereby stalling the pipeline.\nTo do this only when necessary, it would have to track read-write\ndependencies among variables, which seems overly complicated though.\n\n[1]\nhttps://www.postgresql.org/message-id/b4e34135-2bd9-4b8a-94ca-27d760da26d7@manitou-mail.org\n\nBest regards,\n-- \nDaniel Vérité\nPostgreSQL-powered mailer: https://www.manitou-mail.org\nTwitter: @DanielVerite\n\n\n", "msg_date": "Sat, 14 Nov 2020 15:42:50 +0100", "msg_from": "\"Daniel Verite\" <daniel@manitou-mail.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On Fri, Nov 13, 2020 at 5:38 PM Alvaro Herrera <alvherre@alvh.no-ip.org>\nwrote:\n\n> Here's a v25.\n>\n> I made a few more changes to the docs per David's suggestions; I also\n> reordered the sections quite a bit. It's now like this:\n> * Batch Mode\n> * Using Batch Mode\n> * Issuing Queries\n> * Processing Results\n> * Error Handling\n> * Interleaving Result Processing and Query Dispatch\n> * Ending Batch Mode\n> * Functions Associated with Batch Mode\n> * When to Use Batching\n>\n\nThanks!\n\nI like the new flow and changes. I've attached a patch that covers some\nmissing commas and typos along with a few parts that made me pause.\n\nThe impact of memory came out of nowhere under the non-blocking mode\ncommentary. I took a stab at incorporating it more broadly.\n\nThe \"are error conditions\" might be a well-known phrasing to those using\nlibpq but that sentence reads odd to me. I did try to make the example\nlisting flow a bit better and added a needed comma.\n\nTried to clean up a few phrasings after that. The error handling part I'm\nnot especially happy with but I think it's closer and more useful than just\n\"emitted during error handling\" - it gets emitted upon error, handling is a\nclient concern.\n\nSeems odd to say the new feature was introduced in v14.0, the .0 seems ok\nto imply. I didn't actually fix it in the attached but \"the PostgreSQL 14\nversion of libpq\" is going to become outdated quickly, better just to drop\nit.\n\n\"The batch API was introduced in PostgreSQL 14, but clients can use batches\non servers supporting v3 of the extended query protocol, potentially going\nas far back as version 7.4.\"\n\nDavid J.", "msg_date": "Mon, 16 Nov 2020 16:29:19 -0700", "msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On 2020-Nov-14, Daniel Verite wrote:\n\n> The patch I posted in [1] was pretty simple, but at the time, query\n> results were always discarded. Now that pgbench can instantiate\n> variables from query results, a script can do:\n> select 1 as var \\gset\n> select :var;\n> This kind of sequence wouldn't work in batch mode since it\n> sends queries before getting results of previous queries.\n> \n> So maybe \\gset should be rejected when inside a batch section.\n\nHah.\n\nHacking pgbench extensively is beyond what I'm willing to do for this\nfeature at this time. Making \\gset rejected in a batch section sounds\nsimple enough and supports \\beginbatch et al sufficiently to compare\nperformance, so I'm OK with a patch that does that. That'd be a small\nextension to your previous patch, if I understand correctly.\n\nIf you or others want to send patches to extend batch support with\nread-write tracking for variables, feel free, but I hereby declare that\nI'm not taking immediate responsibility for getting them committed.\n\n\n\n", "msg_date": "Wed, 18 Nov 2020 14:51:34 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "Hi\n\nOn Wed, Nov 18, 2020, at 09:51, Alvaro Herrera wrote:\n> On 2020-Nov-14, Daniel Verite wrote:\n> \n> > The patch I posted in [1] was pretty simple, but at the time, query\n> > results were always discarded. Now that pgbench can instantiate\n> > variables from query results, a script can do:\n> > select 1 as var \\gset\n> > select :var;\n> > This kind of sequence wouldn't work in batch mode since it\n> > sends queries before getting results of previous queries.\n> > \n> > So maybe \\gset should be rejected when inside a batch section.\n> \n> Hah.\n> \n> Hacking pgbench extensively is beyond what I'm willing to do for this\n> feature at this time. Making \\gset rejected in a batch section sounds\n> simple enough and supports \\beginbatch et al sufficiently to compare\n> performance, so I'm OK with a patch that does that. That'd be a small\n> extension to your previous patch, if I understand correctly.\n> \n> If you or others want to send patches to extend batch support with\n> read-write tracking for variables, feel free, but I hereby declare that\n> I'm not taking immediate responsibility for getting them committed.\n\nI think minimal support is entirely sufficient initially.\n\nAndres\n\n\n", "msg_date": "Wed, 18 Nov 2020 15:17:36 -0800", "msg_from": "\"Andres Freund\" <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "Hi,\n\nHere's a new version with the pgbench support included.\n\nBest regards,\n-- \nDaniel Vérité\nPostgreSQL-powered mailer: https://www.manitou-mail.org\nTwitter: @DanielVerite", "msg_date": "Mon, 23 Nov 2020 22:58:34 +0100", "msg_from": "\"Daniel Verite\" <daniel@manitou-mail.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On 2020-Nov-23, Daniel Verite wrote:\n\n> Hi,\n> \n> Here's a new version with the pgbench support included.\n\nThanks, incorporated into my local copy.\n\n\n\n", "msg_date": "Mon, 23 Nov 2020 19:15:39 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "Thanks David Johnston and Daniel V�rit�, I have incorporated your\nchanges into this patch, which is now v26. Also, it's been rebased on\ncurrent sources.\n\nI've been using the new PQtrace() stuff to verify the behavior of the\nnew feature. It's not perfect, but at least it doesn't crash\nimmediately as it did when I tried a few weeks ago. There are\nimperfections that I think are due to bugs in the PQtrace\nimplementation, not in this patch.\n\n-- \n�lvaro Herrera 39�49'30\"S 73�17'W\n\"El conflicto es el camino real hacia la uni�n\"", "msg_date": "Thu, 21 Jan 2021 20:39:30 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "As you can see in an XXX comment in the libpq test program, the current\nimplementation has the behavior that PQgetResult() returns NULL after a\nbatch is finished and has reported PGRES_BATCH_END. I don't know if\nthere's a hard reason to do that, but I'd like to supress it because it\nseems weird and out of place.\n\n-- \n�lvaro Herrera 39�49'30\"S 73�17'W\n\n\n", "msg_date": "Thu, 21 Jan 2021 20:43:26 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "Hi,\n\n+ commandFailed(st, \"SQL\", \"\\\\gset and \\\\aset are not\nallowed in a batch section\");\n\nIt seems '\\\\gset or \\\\aset is not ' would correspond to the check more\nclosely.\n\n+ if (my_command->argc != 1)\n+ syntax_error(source, lineno, my_command->first_line,\nmy_command->argv[0],\n\nIt is possible that my_command->argc == 0 (where my_command->argv[0]\nshouldn't be accessed) ?\n\n+ appendPQExpBufferStr(&conn->errorMessage,\n+ libpq_gettext(\"cannot queue commands\nduring COPY\\n\"));\n+ return false;\n+ break;\n\nIs the break necessary ? Similar comment for pqBatchProcessQueue().\n\n+int\n+PQexitBatchMode(PGconn *conn)\n\nSince either 0 or 1 is returned, maybe change the return type to bool.\nAlso, the function operates on PGconn - should the function be static\n(pqBatchProcessQueue is) ?\n\nCheers\n\nOn Thu, Jan 21, 2021 at 3:39 PM Alvaro Herrera <alvherre@alvh.no-ip.org>\nwrote:\n\n> Thanks David Johnston and Daniel Vérité, I have incorporated your\n> changes into this patch, which is now v26. Also, it's been rebased on\n> current sources.\n>\n> I've been using the new PQtrace() stuff to verify the behavior of the\n> new feature. It's not perfect, but at least it doesn't crash\n> immediately as it did when I tried a few weeks ago. There are\n> imperfections that I think are due to bugs in the PQtrace\n> implementation, not in this patch.\n>\n> --\n> Álvaro Herrera 39°49'30\"S 73°17'W\n> \"El conflicto es el camino real hacia la unión\"\n>\n\nHi,+                       commandFailed(st, \"SQL\", \"\\\\gset and \\\\aset are not allowed in a batch section\");It seems '\\\\gset or \\\\aset is not ' would correspond to the check more closely.+       if (my_command->argc != 1)+           syntax_error(source, lineno, my_command->first_line, my_command->argv[0],It is possible that my_command->argc == 0 (where my_command->argv[0] shouldn't be accessed) ?+               appendPQExpBufferStr(&conn->errorMessage,+                                 libpq_gettext(\"cannot queue commands during COPY\\n\"));+               return false;+               break;Is the break necessary ? Similar comment for pqBatchProcessQueue().+int+PQexitBatchMode(PGconn *conn)Since either 0 or 1 is returned, maybe change the return type to bool.Also, the function operates on PGconn - should the function be static (pqBatchProcessQueue is) ?CheersOn Thu, Jan 21, 2021 at 3:39 PM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:Thanks David Johnston and Daniel Vérité, I have incorporated your\nchanges into this patch, which is now v26.  Also, it's been rebased on\ncurrent sources.\n\nI've been using the new PQtrace() stuff to verify the behavior of the\nnew feature.  It's not perfect, but at least it doesn't crash\nimmediately as it did when I tried a few weeks ago.  There are\nimperfections that I think are due to bugs in the PQtrace\nimplementation, not in this patch.\n\n-- \nÁlvaro Herrera                            39°49'30\"S 73°17'W\n\"El conflicto es el camino real hacia la unión\"", "msg_date": "Thu, 21 Jan 2021 16:14:55 -0800", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On 2021-Jan-21, Alvaro Herrera wrote:\n\n> As you can see in an XXX comment in the libpq test program, the current\n> implementation has the behavior that PQgetResult() returns NULL after a\n> batch is finished and has reported PGRES_BATCH_END. I don't know if\n> there's a hard reason to do that, but I'd like to supress it because it\n> seems weird and out of place.\n\nHello Craig, a question for you since this API is your devising. I've\nbeen looking at changing the way this works to prevent those NULL\nreturns from PQgetResult. That is, instead of having what seems like a\n\"NULL separator\" of query results, you'd just get the PGRES_BATCH_END to\nsignify a batch end (not a NULL result after the BATCH_END); and the\nnormal PGRES_COMMAND_OK or PGRES_TUPLES_OK etc when the result of a\ncommand has been sent. It's not working yet so I'm not sending an\nupdated patch, but I wanted to know if you had a rationale for including\nthis NULL return \"separator\" or was it just a convenience because of how\nthe code grew together.\n\nSuch a decision has obvious consequences for the test program (which\nright now expects that PQgetResult() returns NULL at each step); and\nnaturally for libpq's internal state machine that controls how it all\nworks.\n\nThanks,\n\n-- \n�lvaro Herrera 39�49'30\"S 73�17'W\n\n\n", "msg_date": "Wed, 10 Feb 2021 20:51:47 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On Thu, 11 Feb 2021 at 07:51, Alvaro Herrera <alvherre@alvh.no-ip.org>\nwrote:\n\n> On 2021-Jan-21, Alvaro Herrera wrote:\n>\n> > As you can see in an XXX comment in the libpq test program, the current\n> > implementation has the behavior that PQgetResult() returns NULL after a\n> > batch is finished and has reported PGRES_BATCH_END. I don't know if\n> > there's a hard reason to do that, but I'd like to supress it because it\n> > seems weird and out of place.\n>\n> Hello Craig, a question for you since this API is your devising. I've\n> been looking at changing the way this works to prevent those NULL\n> returns from PQgetResult. That is, instead of having what seems like a\n> \"NULL separator\" of query results, you'd just get the PGRES_BATCH_END to\n> signify a batch end (not a NULL result after the BATCH_END); and the\n> normal PGRES_COMMAND_OK or PGRES_TUPLES_OK etc when the result of a\n> command has been sent. It's not working yet so I'm not sending an\n> updated patch, but I wanted to know if you had a rationale for including\n> this NULL return \"separator\" or was it just a convenience because of how\n> the code grew together.\n>\n\nThe existing API for libpq actually specifies[1] that you should call\nPQgetResult() until it returns NULL:\n\n> After successfully calling PQsendQuery, call PQgetResult one or more\ntimes to obtain the results. PQsendQuery cannot be called again (on the\nsame connection) until PQgetResult has returned a null pointer, indicating\nthat the command is done.\n\nSimilarly, in single-row mode, the existing API specifies that you should\ncall PQgetResult() until it returns NULL.\n\nAlso, IIRC the protocol already permits multiple result sets to be\nreturned, and the caller cannot safely assume that a single PQsendQuery()\nwill produce only a single result set. (I really should write a test\nextension that exercises that and how libpq reacts to it.)\n\nThat's why I went for the NULL return. I think. It's been a while now so\nit's a bit fuzzy.\n\nI would definitely like an API that does not rely on testing for a NULL\nreturn. Especially since NULL return can be ambiguous in the context of\nrow-at-a-time mode. New explicit enumerations for PGresult would make a lot\nmore sense.\n\nSo +1 from me for the general idea. I need to look at the patch as it has\nevolved soon too.\n\nRemember that the original patch I submitted for this was a 1-day weekend\nhack and proof of concept to show that libpq could be modified to support\nquery pipelining (and thus batching too), so I could illustrate the\nperformance benefits that could be attained by doing so. I'd been aware of\nthe benefits and the protocol's ability to support it for some time thanks\nto working on PgJDBC, but couldn't get anyone interested without some C\ncode to demonstrate it, so I wrote some. I am not going to argue that the\nAPI I added for it is ideal in any way, and happy to see improvements.\n\nThe only change I would very strongly object to would be anything that\nturned this into a *batch* mode without query-pipelining support. If you\nhave to queue all the queries up in advance then send them as a batch and\nwait for all the results, you miss out on a lot of the potential\nround-trip-time optimisations and you add initial latency. So long as there\nis a way to \"send A\", \"send B\", \"send C\", \"read results from A\", \"send D\",\nand there's a way for the application to associate some kind of state (an\napplication specific id or index, a pointer to an application query-queue\nstruct, whatever) so it can match queries to results ... then I'm happy.\n\n[1]\nhttps://www.postgresql.org/docs/current/libpq-async.html#LIBPQ-PQSENDQUERY\n\nOn Thu, 11 Feb 2021 at 07:51, Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:On 2021-Jan-21, Alvaro Herrera wrote:\n\n> As you can see in an XXX comment in the libpq test program, the current\n> implementation has the behavior that PQgetResult() returns NULL after a\n> batch is finished and has reported PGRES_BATCH_END.  I don't know if\n> there's a hard reason to do that, but I'd like to supress it because it\n> seems weird and out of place.\n\nHello Craig, a question for you since this API is your devising.  I've\nbeen looking at changing the way this works to prevent those NULL\nreturns from PQgetResult.  That is, instead of having what seems like a\n\"NULL separator\" of query results, you'd just get the PGRES_BATCH_END to\nsignify a batch end (not a NULL result after the BATCH_END); and the\nnormal PGRES_COMMAND_OK or PGRES_TUPLES_OK etc when the result of a\ncommand has been sent.  It's not working yet so I'm not sending an\nupdated patch, but I wanted to know if you had a rationale for including\nthis NULL return \"separator\" or was it just a convenience because of how\nthe code grew together.The existing API for libpq actually specifies[1] that you should call PQgetResult() until it returns NULL:> After successfully calling PQsendQuery, call PQgetResult one or more times to obtain the results. PQsendQuery cannot be called again (on the same connection) until PQgetResult has returned a null pointer, indicating that the command is done.Similarly, in single-row mode, the existing API specifies that you should call PQgetResult() until it returns NULL.Also, IIRC the protocol already permits multiple result sets to be returned, and the caller cannot safely assume that a single PQsendQuery() will produce only a single result set. (I really should write a test extension that exercises that and how libpq reacts to it.)That's why I went for the NULL return. I think. It's been a while now so it's a bit fuzzy.I would definitely like an API that does not rely on testing for a NULL return. Especially since NULL return can be ambiguous in the context of row-at-a-time mode. New explicit enumerations for PGresult would make a lot more sense.So +1 from me for the general idea. I need to look at the patch as it has evolved soon too.Remember that the original patch I submitted for this was a 1-day weekend hack and proof of concept to show that libpq could be modified to support query pipelining (and thus batching too), so I could illustrate the performance benefits that could be attained by doing so. I'd been aware of the benefits and the protocol's ability to support it for some time thanks to working on PgJDBC, but couldn't get anyone interested without some C code to demonstrate it, so I wrote some. I am not going to argue that the API I added for it is ideal in any way, and happy to see improvements.The only change I would very strongly object to would be anything that turned this into a *batch* mode without query-pipelining support. If you have to queue all the queries up in advance then send them as a batch and wait for all the results, you miss out on a lot of the potential round-trip-time optimisations and you add initial latency. So long as there is a way to \"send A\", \"send B\", \"send C\", \"read results from A\", \"send D\", and there's a way for the application to associate some kind of state (an application specific id or index, a pointer to an application query-queue struct, whatever)  so it can match queries to results ... then I'm happy.[1] https://www.postgresql.org/docs/current/libpq-async.html#LIBPQ-PQSENDQUERY", "msg_date": "Tue, 16 Feb 2021 09:19:27 +0800", "msg_from": "Craig Ringer <craig.ringer@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On Tue, 16 Feb 2021 at 09:19, Craig Ringer <craig.ringer@enterprisedb.com>\nwrote:\n>\n> So long as there is a way to \"send A\", \"send B\", \"send C\", \"read results\n> from A\", \"send D\", and there's a way for the application to associate some\n> kind of state (an application specific id or index, a pointer to an\n> application query-queue struct, whatever) so it can match queries to\n> results ... then I'm happy.\n>\n\nFWIW I'm also thinking of revising the docs to mostly use the term\n\"pipeline\" instead of \"batch\". Use \"pipelining and batching\" in the chapter\ntopic, and mention \"batch\" in the index, and add a para that explains how\nto run batches on top of pipelining, but otherwise use the term \"pipeline\"\nnot \"batch\".\n\nThat's because pipelining isn't actually batching, and using it as a naïve\nbatch interface will get you in trouble. If you PQsendQuery(...) a long\nlist of queries without consuming results, you'll block unless you're in\nlibpq's nonblocking-send mode. You'll then be deadlocked because the server\ncan't send results until you consume some (tx buffer full) and can't\nconsume queries until it can send some results, but you can't consume\nresults because you're blocked on a send that'll never end.\n\nAn actual batch interface where you can bind and send a long list of\nqueries might be worthwhile, but should be addressed separately, and it'd\nbe confusing if this pipelining interface claimed the term \"batch\". I'm not\nconvinced enough application developers actually code directly against\nlibpq for it to be worth creating a pretty batch interface where you can\nsubmit (say) an array of struct PQbatchEntry { const char * query, int\nnparams, ... } to a PQsendBatch(...) and let libpq handle the socket I/O\nfor you. But if someone wants to add one later it'll be easier if we don't\nuse the term \"batch\" for the pipelining feature.\n\nI'll submit a reworded patch in a bit.\n\nOn Tue, 16 Feb 2021 at 09:19, Craig Ringer <craig.ringer@enterprisedb.com> wrote:So long as there is a way to \"send A\", \"send B\", \"send C\", \"read results from A\", \"send D\", and there's a way for the application to associate some kind of state (an application specific id or index, a pointer to an application query-queue struct, whatever)  so it can match queries to results ... then I'm happy.FWIW I'm also thinking of revising the docs to mostly use the term \"pipeline\" instead of \"batch\". Use \"pipelining and batching\" in the chapter topic, and mention \"batch\" in the index, and add a para that explains how to run batches on top of pipelining, but otherwise use the term \"pipeline\" not \"batch\".That's because pipelining isn't actually batching, and using it as a naïve batch interface will get you in trouble. If you PQsendQuery(...) a long list of queries without consuming results, you'll block unless you're in libpq's nonblocking-send mode. You'll then be deadlocked because the server can't send results until you consume some (tx buffer full) and can't consume queries until it can send some results, but you can't consume results because you're blocked on a send that'll never end.An actual batch interface where you can bind and send a long list of queries might be worthwhile, but should be addressed separately, and it'd be confusing if this pipelining interface claimed the term \"batch\". I'm not convinced enough application developers actually code directly against libpq for it to be worth creating a pretty batch interface where you can submit (say) an array of struct PQbatchEntry { const char * query, int nparams, ... } to a PQsendBatch(...) and let libpq handle the socket I/O for you. But if someone wants to add one later it'll be easier if we don't use the term \"batch\" for the pipelining feature.I'll submit a reworded patch in a bit.", "msg_date": "Tue, 16 Feb 2021 09:38:56 +0800", "msg_from": "Craig Ringer <craig.ringer@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On 2021-Feb-16, Craig Ringer wrote:\n\n> FWIW I'm also thinking of revising the docs to mostly use the term\n> \"pipeline\" instead of \"batch\". Use \"pipelining and batching\" in the chapter\n> topic, and mention \"batch\" in the index, and add a para that explains how\n> to run batches on top of pipelining, but otherwise use the term \"pipeline\"\n> not \"batch\".\n\nHmm, this is a good point. It means I have a lot of API renaming to do.\nI'll get on it now and come back with a proposal.\n\n-- \n�lvaro Herrera Valdivia, Chile\n\n\n", "msg_date": "Tue, 16 Feb 2021 13:27:50 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "Here's a new version, where I've renamed everything to \"pipeline\". I\nthink the docs could use some additional tweaks now in order to make a\ncoherent story on pipeline mode, how it can be used in a batched\nfashion, etc.\n\nHere's the renames I applied. It's mostly mechanical, except\nPQbatchSendQueue is now PQsendPipeline:\n\n\tPQBatchStatus -> PGpipelineStatus (enum)\n\tPQBATCH_MODE_OFF -> PQ_PIPELINE_OFF\n\tPQBATCH_MODE_ON -> PQ_PIPELINE_ON\n\tPQBATCH_MODE_ABORTED -> PQ_PIPELINE_ABORTED\n\tPQbatchStatus -> PQpipelineStatus (function)\n\tPQenterBatchMode -> PQenterPipelineMode\n\tPQexitBatchMode -> PQexitPipelineMode\n\tPQbatchSendQueue -> PQsendPipeline\n\tPGRES_BATCH_END -> PGRES_PIPELINE_END\n\tPGRES_BATCH_ABORTED -> PGRES_PIPELINE_ABORTED\n\nAlso, PQbatchStatus(conn) returns enum PGpipelineStatus (it previously\nreturned int).\n\nI'm tempted to rename PGASYNC_QUEUED to PGASYNC_PIPELINE_IDLE (not sure\nif PGASYNC_PIPELINE_READY fits better with the existing one).\n\n\nIn pgbench, I changed the metacommands to be \\startpipeline and\n\\endpipeline. There's a failing Assert() there which I commented out;\nneeds fixed.\n\n-- \n�lvaro Herrera 39�49'30\"S 73�17'W", "msg_date": "Tue, 16 Feb 2021 20:13:50 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "Hi,\n+ if (querymode == QUERY_SIMPLE)\n+ {\n+ commandFailed(st, \"startpipeline\", \"cannot use pipeline mode\nwith the simple query protocol\");\n+ st->state = CSTATE_ABORTED;\n+ return CSTATE_ABORTED;\n\nI wonder why the st->state is only assigned for this if block. The state is\nnot set for other cases where CSTATE_ABORTED is returned.\n\nShould PQ_PIPELINE_OFF be returned for the following case ?\n\n+PQpipelineStatus(const PGconn *conn)\n+{\n+ if (!conn)\n+ return false;\n\nCheers\n\nOn Tue, Feb 16, 2021 at 3:14 PM Alvaro Herrera <alvherre@alvh.no-ip.org>\nwrote:\n\n> Here's a new version, where I've renamed everything to \"pipeline\". I\n> think the docs could use some additional tweaks now in order to make a\n> coherent story on pipeline mode, how it can be used in a batched\n> fashion, etc.\n>\n> Here's the renames I applied. It's mostly mechanical, except\n> PQbatchSendQueue is now PQsendPipeline:\n>\n> PQBatchStatus -> PGpipelineStatus (enum)\n> PQBATCH_MODE_OFF -> PQ_PIPELINE_OFF\n> PQBATCH_MODE_ON -> PQ_PIPELINE_ON\n> PQBATCH_MODE_ABORTED -> PQ_PIPELINE_ABORTED\n> PQbatchStatus -> PQpipelineStatus (function)\n> PQenterBatchMode -> PQenterPipelineMode\n> PQexitBatchMode -> PQexitPipelineMode\n> PQbatchSendQueue -> PQsendPipeline\n> PGRES_BATCH_END -> PGRES_PIPELINE_END\n> PGRES_BATCH_ABORTED -> PGRES_PIPELINE_ABORTED\n>\n> Also, PQbatchStatus(conn) returns enum PGpipelineStatus (it previously\n> returned int).\n>\n> I'm tempted to rename PGASYNC_QUEUED to PGASYNC_PIPELINE_IDLE (not sure\n> if PGASYNC_PIPELINE_READY fits better with the existing one).\n>\n>\n> In pgbench, I changed the metacommands to be \\startpipeline and\n> \\endpipeline. There's a failing Assert() there which I commented out;\n> needs fixed.\n>\n> --\n> Álvaro Herrera 39°49'30\"S 73°17'W\n>\n\nHi,+       if (querymode == QUERY_SIMPLE)+       {+           commandFailed(st, \"startpipeline\", \"cannot use pipeline mode with the simple query protocol\");+           st->state = CSTATE_ABORTED;+           return CSTATE_ABORTED;I wonder why the st->state is only assigned for this if block. The state is not set for other cases where CSTATE_ABORTED is returned.Should PQ_PIPELINE_OFF be returned for the following case ?+PQpipelineStatus(const PGconn *conn)+{+   if (!conn)+       return false;CheersOn Tue, Feb 16, 2021 at 3:14 PM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:Here's a new version, where I've renamed everything to \"pipeline\".  I\nthink the docs could use some additional tweaks now in order to make a\ncoherent story on pipeline mode, how it can be used in a batched\nfashion, etc.\n\nHere's the renames I applied.  It's mostly mechanical, except\nPQbatchSendQueue is now PQsendPipeline:\n\n        PQBatchStatus -> PGpipelineStatus (enum)\n        PQBATCH_MODE_OFF -> PQ_PIPELINE_OFF\n        PQBATCH_MODE_ON -> PQ_PIPELINE_ON\n        PQBATCH_MODE_ABORTED -> PQ_PIPELINE_ABORTED\n        PQbatchStatus -> PQpipelineStatus (function)\n        PQenterBatchMode -> PQenterPipelineMode\n        PQexitBatchMode -> PQexitPipelineMode\n        PQbatchSendQueue -> PQsendPipeline\n        PGRES_BATCH_END -> PGRES_PIPELINE_END\n        PGRES_BATCH_ABORTED -> PGRES_PIPELINE_ABORTED\n\nAlso, PQbatchStatus(conn) returns enum PGpipelineStatus (it previously\nreturned int).\n\nI'm tempted to rename PGASYNC_QUEUED to PGASYNC_PIPELINE_IDLE (not sure\nif PGASYNC_PIPELINE_READY fits better with the existing one).\n\n\nIn pgbench, I changed the metacommands to be \\startpipeline and\n\\endpipeline.  There's a failing Assert() there which I commented out;\nneeds fixed.\n\n-- \nÁlvaro Herrera                            39°49'30\"S 73°17'W", "msg_date": "Tue, 16 Feb 2021 15:45:08 -0800", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "Hello, thanks for looking at this patch.\n\nOn 2021-Feb-16, Zhihong Yu wrote:\n\n> + if (querymode == QUERY_SIMPLE)\n> + {\n> + commandFailed(st, \"startpipeline\", \"cannot use pipeline mode\n> with the simple query protocol\");\n> + st->state = CSTATE_ABORTED;\n> + return CSTATE_ABORTED;\n> \n> I wonder why the st->state is only assigned for this if block. The state is\n> not set for other cases where CSTATE_ABORTED is returned.\n\nYeah, that's a simple oversight. We don't need to set st->state,\nbecause the caller sets it to the value we return.\n\n> Should PQ_PIPELINE_OFF be returned for the following case ?\n> \n> +PQpipelineStatus(const PGconn *conn)\n> +{\n> + if (!conn)\n> + return false;\n\nYep.\n\nThanks\n\n-- \n�lvaro Herrera 39�49'30\"S 73�17'W\n\n\n", "msg_date": "Fri, 19 Feb 2021 15:35:09 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On 2021-Jan-21, Zhihong Yu wrote:\n\n> It seems '\\\\gset or \\\\aset is not ' would correspond to the check more\n> closely.\n> \n> + if (my_command->argc != 1)\n> + syntax_error(source, lineno, my_command->first_line,\n> my_command->argv[0],\n> \n> It is possible that my_command->argc == 0 (where my_command->argv[0]\n> shouldn't be accessed) ?\n\nNo -- process_backslash_command reads the word and sets it as argv[0].\n\n> + appendPQExpBufferStr(&conn->errorMessage,\n> + libpq_gettext(\"cannot queue commands\n> during COPY\\n\"));\n> + return false;\n> + break;\n> \n> Is the break necessary ? Similar comment for pqBatchProcessQueue().\n\nNot necessary. I removed them.\n\n> +int\n> +PQexitBatchMode(PGconn *conn)\n> \n> Since either 0 or 1 is returned, maybe change the return type to bool.\n\nI was kinda tempted to do that, but in reality a lot of libpq's API is\ndefined like that -- to return 0 (failure)/1 (success) as ints, not\nbools. For example see PQsendQuery(). I'm not inclined to do different\nfor these new functions. (One curious case is PQsetvalue, which returns\nint, and is documented as \"returns zero for failure\" and then uses\n\"return false\").\n\n> Also, the function operates on PGconn - should the function be static\n> (pqBatchProcessQueue is) ?\n\nI don't understand this suggestion. How would an application call it,\nif we make it static?\n\nThanks\n\n-- \n�lvaro Herrera Valdivia, Chile\n\"C�mo ponemos nuestros dedos en la arcilla del otro. Eso es la amistad; jugar\nal alfarero y ver qu� formas se pueden sacar del otro\" (C. Halloway en\nLa Feria de las Tinieblas, R. Bradbury)\n\n\n", "msg_date": "Fri, 19 Feb 2021 15:43:23 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "Hi,\n+static int pqBatchProcessQueue(PGconn *conn);\n\nI was suggesting changing:\n\n+int\n+PQexitBatchMode(PGconn *conn)\n\nto:\n\n+static int\n+PQexitBatchMode(PGconn *conn)\n\nCheers\n\nOn Fri, Feb 19, 2021 at 10:43 AM Alvaro Herrera <alvherre@alvh.no-ip.org>\nwrote:\n\n> On 2021-Jan-21, Zhihong Yu wrote:\n>\n> > It seems '\\\\gset or \\\\aset is not ' would correspond to the check more\n> > closely.\n> >\n> > + if (my_command->argc != 1)\n> > + syntax_error(source, lineno, my_command->first_line,\n> > my_command->argv[0],\n> >\n> > It is possible that my_command->argc == 0 (where my_command->argv[0]\n> > shouldn't be accessed) ?\n>\n> No -- process_backslash_command reads the word and sets it as argv[0].\n>\n> > + appendPQExpBufferStr(&conn->errorMessage,\n> > + libpq_gettext(\"cannot queue commands\n> > during COPY\\n\"));\n> > + return false;\n> > + break;\n> >\n> > Is the break necessary ? Similar comment for pqBatchProcessQueue().\n>\n> Not necessary. I removed them.\n>\n> > +int\n> > +PQexitBatchMode(PGconn *conn)\n> >\n> > Since either 0 or 1 is returned, maybe change the return type to bool.\n>\n> I was kinda tempted to do that, but in reality a lot of libpq's API is\n> defined like that -- to return 0 (failure)/1 (success) as ints, not\n> bools. For example see PQsendQuery(). I'm not inclined to do different\n> for these new functions. (One curious case is PQsetvalue, which returns\n> int, and is documented as \"returns zero for failure\" and then uses\n> \"return false\").\n>\n> > Also, the function operates on PGconn - should the function be static\n> > (pqBatchProcessQueue is) ?\n>\n> I don't understand this suggestion. How would an application call it,\n> if we make it static?\n>\n> Thanks\n>\n> --\n> Álvaro Herrera Valdivia, Chile\n> \"Cómo ponemos nuestros dedos en la arcilla del otro. Eso es la amistad;\n> jugar\n> al alfarero y ver qué formas se pueden sacar del otro\" (C. Halloway en\n> La Feria de las Tinieblas, R. Bradbury)\n>\n\nHi,+static int pqBatchProcessQueue(PGconn *conn);I was suggesting changing:+int+PQexitBatchMode(PGconn *conn)to:+static int+PQexitBatchMode(PGconn *conn)CheersOn Fri, Feb 19, 2021 at 10:43 AM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:On 2021-Jan-21, Zhihong Yu wrote:\n\n> It seems '\\\\gset or \\\\aset is not ' would correspond to the check more\n> closely.\n> \n> +       if (my_command->argc != 1)\n> +           syntax_error(source, lineno, my_command->first_line,\n> my_command->argv[0],\n> \n> It is possible that my_command->argc == 0 (where my_command->argv[0]\n> shouldn't be accessed) ?\n\nNo -- process_backslash_command reads the word and sets it as argv[0].\n\n> +               appendPQExpBufferStr(&conn->errorMessage,\n> +                                 libpq_gettext(\"cannot queue commands\n> during COPY\\n\"));\n> +               return false;\n> +               break;\n> \n> Is the break necessary ? Similar comment for pqBatchProcessQueue().\n\nNot necessary.  I removed them.\n\n> +int\n> +PQexitBatchMode(PGconn *conn)\n> \n> Since either 0 or 1 is returned, maybe change the return type to bool.\n\nI was kinda tempted to do that, but in reality a lot of libpq's API is\ndefined like that -- to return 0 (failure)/1 (success) as ints, not\nbools.  For example see PQsendQuery().  I'm not inclined to do different\nfor these new functions.  (One curious case is PQsetvalue, which returns\nint, and is documented as \"returns zero for failure\" and then uses\n\"return false\").\n\n> Also, the function operates on PGconn - should the function be static\n> (pqBatchProcessQueue is) ?\n\nI don't understand this suggestion.  How would an application call it,\nif we make it static?\n\nThanks\n\n-- \nÁlvaro Herrera       Valdivia, Chile\n\"Cómo ponemos nuestros dedos en la arcilla del otro. Eso es la amistad; jugar\nal alfarero y ver qué formas se pueden sacar del otro\" (C. Halloway en\nLa Feria de las Tinieblas, R. Bradbury)", "msg_date": "Fri, 19 Feb 2021 12:08:15 -0800", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "Hi,\n\nOn 2021-Feb-19, Zhihong Yu wrote:\n\n> Hi,\n> +static int pqBatchProcessQueue(PGconn *conn);\n> \n> I was suggesting changing:\n> \n> +int\n> +PQexitBatchMode(PGconn *conn)\n> \n> to:\n> \n> +static int\n> +PQexitBatchMode(PGconn *conn)\n\nI understand that, but what I'm saying is that it doesn't work.\npqBatchProcessQueue can be static because it's only used internally in\nlibpq, but PQexitBatchMode is supposed to be called by the client\napplication.\n\n-- \n�lvaro Herrera Valdivia, Chile\n\"No necesitamos banderas\n No reconocemos fronteras\" (Jorge Gonz�lez)\n\n\n", "msg_date": "Fri, 19 Feb 2021 17:46:51 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "Hi,\nThanks for the response.\n\nOn Fri, Feb 19, 2021 at 12:46 PM Alvaro Herrera <alvherre@alvh.no-ip.org>\nwrote:\n\n> Hi,\n>\n> On 2021-Feb-19, Zhihong Yu wrote:\n>\n> > Hi,\n> > +static int pqBatchProcessQueue(PGconn *conn);\n> >\n> > I was suggesting changing:\n> >\n> > +int\n> > +PQexitBatchMode(PGconn *conn)\n> >\n> > to:\n> >\n> > +static int\n> > +PQexitBatchMode(PGconn *conn)\n>\n> I understand that, but what I'm saying is that it doesn't work.\n> pqBatchProcessQueue can be static because it's only used internally in\n> libpq, but PQexitBatchMode is supposed to be called by the client\n> application.\n>\n> --\n> Álvaro Herrera Valdivia, Chile\n> \"No necesitamos banderas\n> No reconocemos fronteras\" (Jorge González)\n>\n\nHi,Thanks for the response.On Fri, Feb 19, 2021 at 12:46 PM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:Hi,\n\nOn 2021-Feb-19, Zhihong Yu wrote:\n\n> Hi,\n> +static int pqBatchProcessQueue(PGconn *conn);\n> \n> I was suggesting changing:\n> \n> +int\n> +PQexitBatchMode(PGconn *conn)\n> \n> to:\n> \n> +static int\n> +PQexitBatchMode(PGconn *conn)\n\nI understand that, but what I'm saying is that it doesn't work.\npqBatchProcessQueue can be static because it's only used internally in\nlibpq, but PQexitBatchMode is supposed to be called by the client\napplication.\n\n-- \nÁlvaro Herrera       Valdivia, Chile\n\"No necesitamos banderas\n No reconocemos fronteras\"                  (Jorge González)", "msg_date": "Fri, 19 Feb 2021 13:08:42 -0800", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On Wed, 17 Feb 2021, 07:13 Alvaro Herrera, <alvherre@alvh.no-ip.org> wrote:\n\n> Here's a new version, where I've renamed everything to \"pipeline\".\n\n\nWow. Thanks.\n\nI\n> think the docs could use some additional tweaks now in order to make a\n> coherent story on pipeline mode, how it can be used in a batched\n> fashion, etc.\n>\n\nI'll do that soon and send an update.\n\n>\n>\n\nOn Wed, 17 Feb 2021, 07:13 Alvaro Herrera, <alvherre@alvh.no-ip.org> wrote:Here's a new version, where I've renamed everything to \"pipeline\". Wow. Thanks. I\nthink the docs could use some additional tweaks now in order to make a\ncoherent story on pipeline mode, how it can be used in a batched\nfashion, etc.I'll do that soon and send an update.", "msg_date": "Sat, 20 Feb 2021 08:23:28 +0800", "msg_from": "Craig Ringer <craig.ringer@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On 2021-Feb-20, Craig Ringer wrote:\n\n> On Wed, 17 Feb 2021, 07:13 Alvaro Herrera, <alvherre@alvh.no-ip.org> wrote:\n\n> > I\n> > think the docs could use some additional tweaks now in order to make a\n> > coherent story on pipeline mode, how it can be used in a batched\n> > fashion, etc.\n> \n> I'll do that soon and send an update.\n\nI started to do that, but was sidetracked having a look at error\nhandling while checking one of the claims.\n\nSo now it starts with this:\n\n <sect3 id=\"libpq-pipeline-sending\">\n <title>Issuing Queries</title>\n\n <para>\n After entering pipeline mode, the application dispatches requests using\n <xref linkend=\"libpq-PQsendQueryParams\"/>, \n or its prepared-query sibling\n <xref linkend=\"libpq-PQsendQueryPrepared\"/>.\n These requests are queued on the client-side until flushed to the server;\n this occurs when <xref linkend=\"libpq-PQsendPipeline\"/> is used to\n establish a synchronization point in the pipeline,\n or when <xref linkend=\"libpq-PQflush\"/> is called.\n The functions <xref linkend=\"libpq-PQsendPrepare\"/>,\n <xref linkend=\"libpq-PQsendDescribePrepared\"/>, and\n <xref linkend=\"libpq-PQsendDescribePortal\"/> also work in pipeline mode.\n Result processing is described below.\n </para>\n\n <para>\n The server executes statements, and returns results, in the order the\n client sends them. The server will begin executing the commands in the\n pipeline immediately, not waiting for the end of the pipeline.\n If any statement encounters an error, the server aborts the current\n transaction and skips processing commands in the pipeline until the\n next synchronization point established by <function>PQsendPipeline</function>.\n (This remains true even if the commands in the pipeline would rollback\n the transaction.)\n Query processing resumes after the synchronization point.\n </para>\n\n(Note I changed the wording that \"the pipeline is ended by\nPQsendPipeline\" to \"a synchronization point is established\". Is this\neasily understandable? On re-reading it, I'm not sure it's really an\nimprovement.)\n\nBTW we don't explain why doesn't PQsendQuery work (to wit: because it\nuses \"simple\" query protocol and thus doesn't require the Sync message).\nI think we should either document that, or change things so that\nPQsendQuery no longer uses a 'Q' message when in pipeline mode; instead\nuse extended query protocol. I don't see why we'd force people to use\nPQsendQueryParams when not necessary.\n\nBTW, in my experimentation, the sequence of PGresult that you get when\nhandling a pipeline with errors don't make a lot of sense. I'll spend\nsome more time on it.\n\nWhile at it, as for the PGresult sequence and NULL returns: I think for\nPQexec and maybe PQsendQuery, it makes sense to loop until PQgetResult\nreturns NULL, because you never know how many results are you going to\nget. But for PQsendQueryParams, this is no longer true, because you\ncan't send multiple queries in one query string. So the only way to get\nmultiple results, is by using single-row mode. But that already has its\nown protocol for multiple results, namely to get a stream of\nPGRES_SINGLE_TUPLE terminated by a zero-rows PGRES_TUPLES_OK. So I'm\nnot sure there is a strong need for the mandatory NULL result.\n\n-- \n�lvaro Herrera 39�49'30\"S 73�17'W\n\n\n", "msg_date": "Fri, 19 Feb 2021 22:36:55 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On Wed, Feb 17, 2021 8:14 AM (JST), Alvaro Herrera wrote:\n\nHi Alvaro,\n\n> Here's a new version, where I've renamed everything to \"pipeline\". I think the\n> docs could use some additional tweaks now in order to make a coherent\n> story on pipeline mode, how it can be used in a batched fashion, etc.\n\nI tried applying this patch to test it on top of Iwata-san's libpq trace log [1].\nIn my environment, the compiler complains.\nIt seems that in libpqwalreceiver.c: libpqrcv_exec()\nthe switch for PQresultStatus needs to handle the\ncases for PGRES_PIPELINE_END and PGRES_PIPELINE_ABORTED too.\n\n switch (PQresultStatus(pgres))\n {\n ...\n Case PGRES_PIPELINE_ABORTED:\n \t\t...\n Case PGRES_PIPELINE_ END:\n\nRegards,\nKirk Jamison\n\n[1] https://www.postgresql.org/message-id/flat/1d650278-552a-4bd2-8411-a907fd54446c%40www.fastmail.com#32df02a4e2a08185508a2126e6e0caf1\n\n\n", "msg_date": "Wed, 3 Mar 2021 07:07:59 +0000", "msg_from": "\"k.jamison@fujitsu.com\" <k.jamison@fujitsu.com>", "msg_from_op": false, "msg_subject": "RE: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On 2021-Mar-03, k.jamison@fujitsu.com wrote:\n\n> I tried applying this patch to test it on top of Iwata-san's libpq trace log [1].\n> In my environment, the compiler complains.\n> It seems that in libpqwalreceiver.c: libpqrcv_exec()\n> the switch for PQresultStatus needs to handle the\n> cases for PGRES_PIPELINE_END and PGRES_PIPELINE_ABORTED too.\n\nYeah, I noticed this too and decided to handle these cases as errors.\n\nHere's v28, which includes that fix, and also gets rid of the\nPGASYNC_QUEUED state; I instead made the rest of the code work using the\nexisting PGASYNC_IDLE state. This allows us get rid of a few cases\nwhere we had to report \"internal error: IDLE state unexpected\" in a few\ncases, and was rather pointless. With the current formulation, both\npipeline mode and normal mode share pretty much all state.\n\nAlso, I've renamed PGRES_PIPELINE_END to PGRES_PIPELINE_SYNC, because\nthat's closer to what it means: that result state by no means that\npipeline mode has ended. It only means that you called PQsendPipeline()\nso the server gives you a Sync message.\n\nI'm much more comfortable with this version, so I'm marking the patch as\nReady for Committer in case anybody else wants to look at this before I\npush it.\n\nHowever: on errors, I think it's a bit odd that you get a NULL from\nPQgetResult after getting PGRES_PIPELINE_ABORTED. Maybe I should\nsuppress that. I'm no longer wrestling with the NULL after\nPGRES_PIPELINE_END however, because that's not critical and you can not\nask for it and things work fine.\n\n(Also, the test pipeline.c program in src/test/modules/test_libpq has a\nnew \"transaction\" mode that is not exercised by the TAP program; I'll\nplug that in before commit.)\n\n-- \n�lvaro Herrera Valdivia, Chile", "msg_date": "Wed, 3 Mar 2021 13:34:30 -0300", "msg_from": "'Alvaro Herrera' <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On 2021-Mar-03, 'Alvaro Herrera' wrote:\n\n> I'm much more comfortable with this version, so I'm marking the patch as\n> Ready for Committer in case anybody else wants to look at this before I\n> push it.\n\nActually, I just noticed a pretty serious problem, which is that when we\nreport an error, we don't set \"conn->errQuery\" to the current query but\nto the *previous* query, leading to non-sensical error reports like\n\n$ ./pipeline pipeline_abort\naborted pipeline... ERROR: no existe la funci�n no_such_function(integer)\nLINE 1: INSERT INTO pq_pipeline_demo(itemno) VALUES ($1);\n ^\nHINT: Ninguna funci�n coincide en el nombre y tipos de argumentos. Puede ser necesario agregar conversi�n expl�cita de tipos.\nok\n\n\n(Sorry about the Spanish there, but the gist of the problem is that\nwe're positioning the error cursor on a query that succeeded prior to\nthe query that raised the error.)\n\nThis should obviously not occur. I'm trying to figure out how to repair\nit and not break everything again ...\n\n-- \n�lvaro Herrera Valdivia, Chile\n\n\n", "msg_date": "Wed, 3 Mar 2021 20:42:41 -0300", "msg_from": "'Alvaro Herrera' <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On 2021-Mar-03, 'Alvaro Herrera' wrote:\n\n> This should obviously not occur. I'm trying to figure out how to repair\n> it and not break everything again ...\n\nI think trying to set up the connection state so that the next query\nappears in conn->last_query prior to PQgetResult being called again\nleads to worse breakage. The simplest fix seems to make fe-protocol3.c\naware that in this case, the query is in conn->cmd_queue_head instead,\nas in the attached patch.\n\n-- \n�lvaro Herrera 39�49'30\"S 73�17'W", "msg_date": "Wed, 3 Mar 2021 21:24:29 -0300", "msg_from": "'Alvaro Herrera' <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "I'm proposing some minor changes.\n\n-- \nJustin", "msg_date": "Wed, 3 Mar 2021 18:45:02 -0600", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On 2021-Mar-03, 'Alvaro Herrera' wrote:\n\n> On 2021-Mar-03, 'Alvaro Herrera' wrote:\n> \n> > This should obviously not occur. I'm trying to figure out how to repair\n> > it and not break everything again ...\n> \n> I think trying to set up the connection state so that the next query\n> appears in conn->last_query prior to PQgetResult being called again\n> leads to worse breakage. The simplest fix seems to make fe-protocol3.c\n> aware that in this case, the query is in conn->cmd_queue_head instead,\n> as in the attached patch.\n\nI wonder if it would make sense to get rid of conn->last_query\ncompletely and just rely always on conn->cmd_queue_head, where the\nnormal (non-pipeline) would use the first entry of the command queue.\nThat might end up being simpler than pipeline mode \"pretending\" to take\nover ->last_query.\n\n-- \n�lvaro Herrera 39�49'30\"S 73�17'W\n\"La verdad no siempre es bonita, pero el hambre de ella s�\"\n\n\n", "msg_date": "Wed, 3 Mar 2021 22:51:08 -0300", "msg_from": "'Alvaro Herrera' <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On Wed, Mar 3, 2021 at 5:45 PM Justin Pryzby <pryzby@telsasoft.com> wrote:\n\n> I'm proposing some minor changes.\n>\n>\nSome additional tweaks/comments for the documentation with the edit\nproposed edits:\n\n(edit) + <function>PQresultStatus</function>, will report a\n\nRemove the comma\n\n(orig) + the failed operation are skipped entirely. The same behaviour\nholds if the\n\nWe seem to use \"behavior\" more frequently\n\n(edit) + From the client perspective, after\n<function>PQresultStatus</function>\n\nPossessive \"client's perspective\"\n\n(edit) + its expected results queue. Based on available memory,\nresults from the\n\n\"its corresponding results queue\" - to go along with this change:\n- of the order in which it sent queries and the expected results.\n+ of the order in which it sent queries, to associate them with their\n+ corresponding results.\n\n(orig)\n+ pipeline mode. If the current statement isn't finished processing\n+ or there are results pending for collection with\n\nNeeds a comma after processing.\n\"results pending for collection\" reads oddly to me...not sure what would be\nbetter though...\n\n(edit)\n+ <note>\n+ <para>\n+ The pipeline API was introduced in\n<productname>PostgreSQL</productname> 14.\n+ Pipeline mode is a client-side feature which doesn't require server\n+ support, and works on any server that supports the v3 extended query\n+ protocol.\n+ </para>\n+ </note>\n\nThis note seems like it should be placed either near the very beginning of\nthe feature or incorporated into the feature introduction.\n(orig)\n+ If any statement encounters an error, the server aborts the current\n+(-) transaction and skips processing commands in the pipeline until the\n+ next synchronization point established by\n<function>PQsendPipeline</function>.\n\nI dislike \"skips\" here - even if it doesn't execute a command it still will\nplace a result on the socket so that the client can have something to match\nup with the queries it sent, correct?\n\n+ transaction and creates a PGRES_PIPELINE_ABORTED result for all commands\nin the pipeline until the\n\nDavid J.\n\nOn Wed, Mar 3, 2021 at 5:45 PM Justin Pryzby <pryzby@telsasoft.com> wrote:I'm proposing some minor changes.Some additional tweaks/comments for the documentation with the edit proposed edits:(edit) +     <function>PQresultStatus</function>, will report aRemove the comma(orig) +     the failed operation are skipped entirely. The same behaviour holds if theWe seem to use \"behavior\" more frequently(edit) +     From the client perspective, after <function>PQresultStatus</function>Possessive \"client's perspective\"(edit) +     its expected results queue.  Based on available memory, results from the\"its corresponding results queue\" - to go along with this change:-     of the order in which it sent queries and the expected results.+     of the order in which it sent queries, to associate them with their+     corresponding results.(orig)+       pipeline mode. If the current statement isn't finished processing +       or there are results pending for collection withNeeds a comma after processing.\"results pending for collection\" reads oddly to me...not sure what would be better though...(edit)+   <note>+    <para>+     The pipeline API was introduced in <productname>PostgreSQL</productname> 14.+     Pipeline mode is a client-side feature which doesn't require server+     support, and works on any server that supports the v3 extended query+     protocol.+     </para>+   </note>This note seems like it should be placed either near the very beginning of the feature or incorporated into the feature introduction.(orig)+     If any statement encounters an error, the server aborts the current+(-)     transaction and skips processing commands in the pipeline until the+     next synchronization point established by <function>PQsendPipeline</function>.I dislike \"skips\" here - even if it doesn't execute a command it still will place a result on the socket so that the client can have something to match up with the queries it sent, correct?+ transaction and creates a PGRES_PIPELINE_ABORTED result for all commands in the pipeline until theDavid J.", "msg_date": "Mon, 8 Mar 2021 15:37:16 -0700", "msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" }, { "msg_contents": "On 2021-Mar-03, 'Alvaro Herrera' wrote:\n\n> I wonder if it would make sense to get rid of conn->last_query\n> completely and just rely always on conn->cmd_queue_head, where the\n> normal (non-pipeline) would use the first entry of the command queue.\n> That might end up being simpler than pipeline mode \"pretending\" to take\n> over ->last_query.\n\nI experimented with this today and it appears to be a good change,\nthough I haven't been able to make everything work correctly yet.\n\n-- \n�lvaro Herrera Valdivia, Chile\n\"Entristecido, Wutra (canci�n de Las Barreras)\necha a Freyr a rodar\ny a nosotros al mar\"\n\n\n", "msg_date": "Mon, 8 Mar 2021 20:02:39 -0300", "msg_from": "'Alvaro Herrera' <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: PATCH: Batch/pipelining support for libpq" } ]
[ { "msg_contents": "Hi!\n\nSometimes the output to stdout on Windows on multicore machines does not \ngo through after connecting and disconnecting to the server using the \nPQconnectdbParams and PQfinish functions. I tested on 6 cores.\n\nFirst we appeared this in some pgbench tests.  Then we found that this \nhappens on any console program using PQconnectdbParams and PQfinish.\n\nI am attaching a patch and a script for testing.\n\n-- \nVictor Spirin\nPostgres Professional:http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Mon, 31 Aug 2020 21:20:28 +0300", "msg_from": "Victor Spirin <v.spirin@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Sometimes the output to the stdout in Windows disappears" }, { "msg_contents": "Victor Spirin <v.spirin@postgrespro.ru> writes:\n> Sometimes the output to stdout on Windows on multicore machines does not \n> go through after connecting and disconnecting to the server using the \n> PQconnectdbParams and PQfinish functions. I tested on 6 cores.\n\nHm, why is this not Microsoft's bug to solve?\n\nI do wonder if this report is related to the intermittent ecpg failures\nwe see on Windows machines, such as [1]. The details vary, but it's\nalways a case of a .stdout file ending up empty when it should not be.\nI'd supposed though that it must be something specific to ecpg, since\nwe never see anything like that anywhere but the ecpg tests. Even if\nyou posit that libpq is doing something that somehow compromises stdio,\nthat should affect psql-based tests too.\n\n> I am attaching a patch and a script for testing.\n> [ forced fflush in every snprintf call ]\n\nMy goodness, that's a large hammer you're swinging. What effects has this\nkluge got on performance?\n\nWhile I think you may be on to something, this seems like a truly horrid\nway to \"fix\" it. We need to dig down further and understand what is\nactually happening.\n\n\t\t\tregards, tom lane\n\n[1] https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=dory&dt=2020-08-13%2022%3A15%3A05\n\n\n", "msg_date": "Mon, 31 Aug 2020 14:31:24 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Sometimes the output to the stdout in Windows disappears" }, { "msg_contents": "I only found that calling WSACleanup instead of PQfinish has the same \neffect.\n\nI don't see any big performance issues due to the extra fflush call in \nthis place. I will be glad to find a more elegant solution.\n\nVictor Spirin\nPostgres Professional:http://www.postgrespro.com\nThe Russian Postgres Company\n\n31.08.2020 21:31, Tom Lane пишет:\n> Victor Spirin <v.spirin@postgrespro.ru> writes:\n>> Sometimes the output to stdout on Windows on multicore machines does not\n>> go through after connecting and disconnecting to the server using the\n>> PQconnectdbParams and PQfinish functions. I tested on 6 cores.\n> Hm, why is this not Microsoft's bug to solve?\n>\n> I do wonder if this report is related to the intermittent ecpg failures\n> we see on Windows machines, such as [1]. The details vary, but it's\n> always a case of a .stdout file ending up empty when it should not be.\n> I'd supposed though that it must be something specific to ecpg, since\n> we never see anything like that anywhere but the ecpg tests. Even if\n> you posit that libpq is doing something that somehow compromises stdio,\n> that should affect psql-based tests too.\n>\n>> I am attaching a patch and a script for testing.\n>> [ forced fflush in every snprintf call ]\n> My goodness, that's a large hammer you're swinging. What effects has this\n> kluge got on performance?\n>\n> While I think you may be on to something, this seems like a truly horrid\n> way to \"fix\" it. We need to dig down further and understand what is\n> actually happening.\n>\n> \t\t\tregards, tom lane\n>\n> [1] https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=dory&dt=2020-08-13%2022%3A15%3A05\n>\n>\n\n\n", "msg_date": "Mon, 31 Aug 2020 22:38:36 +0300", "msg_from": "Victor Spirin <v.spirin@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Sometimes the output to the stdout in Windows disappears" }, { "msg_contents": "I happened to try googling for other similar reports, and I found\na very interesting recent thread here:\n\nhttps://github.com/nodejs/node/issues/33166\n\nIt might not have the same underlying cause, of course, but it sure\nsounds familiar. If Node.js are really seeing the same effect,\nthat would point to an underlying Windows bug rather than anything\nPostgres is doing wrong.\n\nIt doesn't look like the Node.js crew got any closer to\nunderstanding the issue than we have, unfortunately. They made\ntheir problem mostly go away by reverting a seemingly-unrelated\npatch. But I can't help thinking that it's a timing-related bug,\nand that patch was just unlucky enough to change the timing of\ntheir tests so that they saw the failure frequently.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 13 Sep 2020 14:37:08 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Sometimes the output to the stdout in Windows disappears" }, { "msg_contents": "Hello hackers,\n\n13.09.2020 21:37, Tom Lane wrote:\n> I happened to try googling for other similar reports, and I found\n> a very interesting recent thread here:\n>\n> https://github.com/nodejs/node/issues/33166\n>\n> It might not have the same underlying cause, of course, but it sure\n> sounds familiar. If Node.js are really seeing the same effect,\n> that would point to an underlying Windows bug rather than anything\n> Postgres is doing wrong.\n>\n> It doesn't look like the Node.js crew got any closer to\n> understanding the issue than we have, unfortunately. They made\n> their problem mostly go away by reverting a seemingly-unrelated\n> patch. But I can't help thinking that it's a timing-related bug,\n> and that patch was just unlucky enough to change the timing of\n> their tests so that they saw the failure frequently.\nI've managed to make a simple reproducer. Please look at the patch attached.\nThere are two things crucial for reproducing the bug:\n    ioctlsocket(sock, FIONBIO, &ioctlsocket_ret); // from pgwin32_socket()\nand\n    WSACleanup();\n\nI still can't understand what affects the effect. With this reproducer I\nget:\nvcregress taptest src\\test\\modules\\connect\n...\nt/000_connect.pl .. # test\n#\nt/000_connect.pl .. 13346/100000\n#   Failed test at t/000_connect.pl line 24.\nt/000_connect.pl .. 16714/100000\n#   Failed test at t/000_connect.pl line 24.\nt/000_connect.pl .. 26216/100000\n#   Failed test at t/000_connect.pl line 24.\nt/000_connect.pl .. 30077/100000\n#   Failed test at t/000_connect.pl line 24.\nt/000_connect.pl .. 36505/100000\n#   Failed test at t/000_connect.pl line 24.\nt/000_connect.pl .. 43647/100000\n#   Failed test at t/000_connect.pl line 24.\nt/000_connect.pl .. 53070/100000\n#   Failed test at t/000_connect.pl line 24.\nt/000_connect.pl .. 54402/100000\n#   Failed test at t/000_connect.pl line 24.\nt/000_connect.pl .. 55685/100000\n#   Failed test at t/000_connect.pl line 24.\nt/000_connect.pl .. 83193/100000\n#   Failed test at t/000_connect.pl line 24.\nt/000_connect.pl .. 99992/100000 # Looks like you failed 10 tests of 100000.\nt/000_connect.pl .. Dubious, test returned 10 (wstat 2560, 0xa00)\nFailed 10/100000 subtests\n\nBut in our test farm the pg_bench test (from the installcheck-world\nsuite that we run with using msys) can fail roughly on each third run.\nPerhaps it depends on I/O load. It seems, that searching files/scanning\ndisk in parallel increases the probability of the glitch.\nI see no solution for this on the postgres side for now, but this\ninformation about Windows quirks could be useful in case someone\nstumbled upon it too.\n\nBest regards,\nAlexander", "msg_date": "Fri, 16 Oct 2020 19:00:00 +0300", "msg_from": "Alexander Lakhin <exclusion@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Sometimes the output to the stdout in Windows disappears" }, { "msg_contents": "Alexander Lakhin <exclusion@gmail.com> writes:\n> I've managed to make a simple reproducer. Please look at the patch attached.\n> There are two things crucial for reproducing the bug:\n>     ioctlsocket(sock, FIONBIO, &ioctlsocket_ret); // from pgwin32_socket()\n> and\n>     WSACleanup();\n\nOh, very interesting.\n\nNow that you have it somewhat in captivity, maybe you could determine\nsome things:\n\n1. Is it only stdout that's affected? What of other stdio streams?\n(Note that testing stderr might be tricky because it's probably\nline-buffered.)\n\n2. Does an fflush() just before, or just after, WSACleanup() fix it?\n\n> I see no solution for this on the postgres side for now, but this\n> information about Windows quirks could be useful in case someone\n> stumbled upon it too.\n\nDepending on your answers to the above, maybe some hack like this\nwould be acceptable:\n\n \tfree(conn);\n \n #ifdef WIN32\n+\tfflush(NULL);\n \tWSACleanup();\n #endif\n }\n\nIt's not very nice for a library to be doing global things like that,\nbut if the alternative is loss of output, maybe we should.\n\nBut wait a minute: I just looked at Microsoft's docs [1] and found\n\n In a multithreaded environment, WSACleanup terminates Windows Sockets\n operations for all threads.\n\nThis makes me (a) wonder if that explains the side-effects on stdio,\nand (b) question why libpq is calling WSACleanup at all.\nWhat if we arranged to call WSAStartup just once, during the first\nlibpq connection-open in a process, and then never did WSACleanup?\nSurely the OS can cope with that, and it eliminates any risk that\nWSACleanup breaks something.\n\n\t\t\tregards, tom lane\n\n[1] https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsacleanup\n\n\n", "msg_date": "Fri, 16 Oct 2020 12:18:32 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Sometimes the output to the stdout in Windows disappears" }, { "msg_contents": "16.10.2020 19:18, Tom Lane wrote:\n> Oh, very interesting.\n> Now that you have it somewhat in captivity, maybe you could determine\n> some things:\n>\n> 1. Is it only stdout that's affected? What of other stdio streams?\n> (Note that testing stderr might be tricky because it's probably\n> line-buffered.)\nstderr is affected too. Just replacing stdout with stderr in connect.c\nand 000_connect.pl gives the same result.\n\nMoreover, the following modification:\n...\n    outfile = fopen(\"out\", \"w\");\n...\n    fprintf(stdout, \"stdout test\\n\");\n    fprintf(stderr, \"stderr test\\n\");\n    fprintf(outfile, \"outfile test\\n\");\n    WSACleanup();\n...\n\n---\nfor (my $i =0; $i < 100000; $i++) {\n    unlink('out');\n    IPC::Run::run(\\@cmd, '>', \\$stdout, '2>', \\$stderr);\n    open(my $fh, '<', 'out') or die $!;\n    my $fileout = <$fh>;\n    ok(defined $fileout && $fileout ne '');\n    close($fh);\n}\n\ndetects similar failures too. (On a fail the out file exists but has\nzero size.)\n\n> 2. Does an fflush() just before, or just after, WSACleanup() fix it?\n\"fflush(NULL);\" just before or after WSACleanup() fixes things.\n\nI've managed to record in ProcMon the activity log for a failed run\n(aside normal runs). Excerpts from the log are attached. As we can see,\nthe failed process doesn't even try to write into IPC-Run's temp file.\n\n> Depending on your answers to the above, maybe some hack like this\n> would be acceptable:\n>\n> \tfree(conn);\n> \n> #ifdef WIN32\n> +\tfflush(NULL);\n> \tWSACleanup();\n> #endif\n> }\n>\n> It's not very nice for a library to be doing global things like that,\n> but if the alternative is loss of output, maybe we should.\nBut now we see that the WSACleanup call is a global thing by itself.\n> But wait a minute: I just looked at Microsoft's docs [1] and found\n>\n> In a multithreaded environment, WSACleanup terminates Windows Sockets\n> operations for all threads.\n>\n> This makes me (a) wonder if that explains the side-effects on stdio,\n> and (b) question why libpq is calling WSACleanup at all.\n> What if we arranged to call WSAStartup just once, during the first\n> libpq connection-open in a process, and then never did WSACleanup?\n> Surely the OS can cope with that, and it eliminates any risk that\n> WSACleanup breaks something.\nWhat bothers me is:\n\n There must be a call to *WSACleanup* for each successful call to\n WSAStartup\n <https://docs.microsoft.com/en-us/windows/desktop/api/winsock/nf-winsock-wsastartup>.\n Only the final *WSACleanup* function call performs the actual\n cleanup. The preceding calls simply decrement an internal reference\n count in the WS2_32.DLL.\n\nSo third-party application developers should understand that when using\nlibpq they would have to call WSACleanup one more time to perform \"the\nactual cleanup\". (And thus WSAStartup is kind of like a global thing too.)\nBut may be it's a way better than to have a confirmed risk of losing data.\n\nBest regards,\nAlexander", "msg_date": "Sat, 17 Oct 2020 11:00:02 +0300", "msg_from": "Alexander Lakhin <exclusion@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Sometimes the output to the stdout in Windows disappears" }, { "msg_contents": "\nOn 10/16/20 12:18 PM, Tom Lane wrote:\n>\n> But wait a minute: I just looked at Microsoft's docs [1] and found\n>\n> In a multithreaded environment, WSACleanup terminates Windows Sockets\n> operations for all threads.\n>\n> This makes me (a) wonder if that explains the side-effects on stdio,\n> and (b) question why libpq is calling WSACleanup at all.\n> What if we arranged to call WSAStartup just once, during the first\n> libpq connection-open in a process, and then never did WSACleanup?\n> Surely the OS can cope with that, and it eliminates any risk that\n> WSACleanup breaks something.\n>\n> \t\t\tregards, tom lane\n>\n> [1] https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsacleanup\n>\n>\n\n\nThis could explain random transient stdout/stderr failures we have seen\nover the years. I think we should at least give your suggestion a try -\nthis is a good time in the dev cycle for such experiments.\n\n\ncheers\n\n\nandrew\n\n\n\n\n\n", "msg_date": "Sat, 17 Oct 2020 09:54:46 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: Sometimes the output to the stdout in Windows disappears" }, { "msg_contents": "Alexander Lakhin <exclusion@gmail.com> writes:\n> 16.10.2020 19:18, Tom Lane wrote:\n>> What if we arranged to call WSAStartup just once, during the first\n>> libpq connection-open in a process, and then never did WSACleanup?\n>> Surely the OS can cope with that, and it eliminates any risk that\n>> WSACleanup breaks something.\n\n> What bothers me is:\n\n> There must be a call to *WSACleanup* for each successful call to\n> WSAStartup\n> <https://docs.microsoft.com/en-us/windows/desktop/api/winsock/nf-winsock-wsastartup>.\n\nYeah, that is a very odd statement. Surely, the Windows kernel manages\nto cope if a program crashes without having done that. So what exactly\nis the downside of intentionally not doing it? There's no reason to\ncare if the Winsock DLL stays loaded until program exit rather than\ngetting unloaded a bit earlier. (If anything, the current code causes\nan unload/reload cycle for each connection when the application makes\na series of PG connections; who could think that's a great idea?)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 17 Oct 2020 11:50:57 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Sometimes the output to the stdout in Windows disappears" }, { "msg_contents": "I wrote:\n> Alexander Lakhin <exclusion@gmail.com> writes:\n>> What bothers me is:\n>> \tThere must be a call to *WSACleanup* for each successful call to\n>> \tWSAStartup\n>> \t<https://docs.microsoft.com/en-us/windows/desktop/api/winsock/nf-winsock-wsastartup>.\n\n> Yeah, that is a very odd statement. Surely, the Windows kernel manages\n> to cope if a program crashes without having done that. So what exactly\n> is the downside of intentionally not doing it?\n\nA bit of grepping showed me that the backend, initdb, and pg_regress\nall call WSAStartup without ever doing WSACleanup, and we've seen no\nill effects from that. So it seems clear that this documentation can\nsafely be ignored.\n\nI propose the attached patch. If this doesn't cause buildfarm problems,\nperhaps we should back-patch it.\n\nBTW, I notice that libpq is asking WSAStartup for Winsock version 1.1,\nwhich is remarkably ancient. Almost everyplace else is asking for\nversion 2.2, which has been current for a decade or two. Shouldn't\nwe update that? (It occurs to me to wonder if this in itself is\nsome kind of problem; I wonder how well Winsock works when there are\nrequests for different API versions in the same program.)\n\n\t\t\tregards, tom lane", "msg_date": "Sat, 17 Oct 2020 14:44:37 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Sometimes the output to the stdout in Windows disappears" }, { "msg_contents": "17.10.2020 21:44, Tom Lane wrote:\n> I propose the attached patch. If this doesn't cause buildfarm problems,\n> perhaps we should back-patch it.\nThank you!\nI've made a simple cmd script to reproduce problems seen on dory:\nhttps://buildfarm.postgresql.org/cgi-bin/show_history.pl?nm=dory&br=HEAD\n\nFOR /L %%I IN (1,1,200) DO call :CHECK %%I\nGOTO :eof\n:CHECK\necho iteration %1\ncall vcregress ecpgcheck\nIF %ERRORLEVEL% NEQ 0 GOTO ERR\nEXIT /B\n:ERR\necho iteration %1 failed\npause\n\nWithout the fix I've got errors on iterations 43, 46, 128, 47, 14, 4,\n27, which approximately corresponds to the ECPG-Check failure frequency\non dory (for HEAD).\nWith the fix all the 200 iterations passed as expected.\nThen I ran the loop again just to be sure and got:\ntest thread/descriptor            ... stderr FAILED       81 ms\niteration 124 failed.\n\ndiff -w -U3\n.../src/interfaces/ecpg/test/expected/thread-descriptor.stderr\n.../src/interfaces/ecpg/test/results/thread-descriptor.stderr\n--- .../src/interfaces/ecpg/test/expected/thread-descriptor.stderr   \n2019-12-04 16:05:46 +0300\n+++ .../src/interfaces/ecpg/test/results/thread-descriptor.stderr   \n2020-10-18 20:20:27 +0300\n@@ -0,0 +1 @@\n+SQL error: descriptor \"mydesc\" not found on line 31\n\nIt's interesting that all failures before the fix were with stdout, but\nthis one is with stderr.\nI'm going to investigate this issue further.\n\nBest regards,\nAlexander\n\n\n", "msg_date": "Sun, 18 Oct 2020 21:00:00 +0300", "msg_from": "Alexander Lakhin <exclusion@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Sometimes the output to the stdout in Windows disappears" }, { "msg_contents": "Alexander Lakhin <exclusion@gmail.com> writes:\n> With the fix all the 200 iterations passed as expected.\n> Then I ran the loop again just to be sure and got:\n> test thread/descriptor            ... stderr FAILED       81 ms\n> iteration 124 failed.\n\nSigh ... still, this:\n\n> diff -w -U3\n> .../src/interfaces/ecpg/test/expected/thread-descriptor.stderr\n> .../src/interfaces/ecpg/test/results/thread-descriptor.stderr\n> --- .../src/interfaces/ecpg/test/expected/thread-descriptor.stderr   \n> 2019-12-04 16:05:46 +0300\n> +++ .../src/interfaces/ecpg/test/results/thread-descriptor.stderr   \n> 2020-10-18 20:20:27 +0300\n> @@ -0,0 +1 @@\n> +SQL error: descriptor \"mydesc\" not found on line 31\n\ndoes not look like the same kind of failure as what we've been dealing\nwith up to now. So maybe what we've got is that we fixed the stdio\nloss problem, and now the error rate is down to the point where we can\nnotice other, even-lower-probability issues.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 18 Oct 2020 14:04:51 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Sometimes the output to the stdout in Windows disappears" }, { "msg_contents": "I wrote:\n>> diff -w -U3\n>> .../src/interfaces/ecpg/test/expected/thread-descriptor.stderr\n>> .../src/interfaces/ecpg/test/results/thread-descriptor.stderr\n>> --- .../src/interfaces/ecpg/test/expected/thread-descriptor.stderr   \n>> 2019-12-04 16:05:46 +0300\n>> +++ .../src/interfaces/ecpg/test/results/thread-descriptor.stderr   \n>> 2020-10-18 20:20:27 +0300\n>> @@ -0,0 +1 @@\n>> +SQL error: descriptor \"mydesc\" not found on line 31\n\n> does not look like the same kind of failure as what we've been dealing\n> with up to now. So maybe what we've got is that we fixed the stdio\n> loss problem, and now the error rate is down to the point where we can\n> notice other, even-lower-probability issues.\n\nYeah, I think so. I grepped the buildfarm logs for similar failures and\nfound three occurrences:\n\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=bowerbird&dt=2019-02-03%2018%3A36%3A05\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=bowerbird&dt=2019-01-17%2014%3A30%3A07\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=drongo&dt=2020-01-02%2018%3A03%3A52\n\nAll of these are in the thread/descriptor test, failing at the deallocate\nstep in \n\n\tfor (i = 1; i <= REPEATS; ++i)\n\t{\n\t\tEXEC SQL ALLOCATE DESCRIPTOR mydesc;\n\t\tEXEC SQL DEALLOCATE DESCRIPTOR mydesc;\n\t}\n\nwhere the test is running several of these in different threads.\nI wonder whether there's some missing thread-locking in the ECPG\ndescriptor support. It is odd though that we have seen this only\non Windows members. Low-probability or not, you'd think we'd have\nsome similar reports from non-Windows critters if it were possible.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 18 Oct 2020 14:24:06 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Sometimes the output to the stdout in Windows disappears" }, { "msg_contents": "18.10.2020 21:04, Tom Lane wrote:\n> Alexander Lakhin <exclusion@gmail.com> writes:\n>> @@ -0,0 +1 @@\n>> +SQL error: descriptor \"mydesc\" not found on line 31\n> does not look like the same kind of failure as what we've been dealing\n> with up to now. So maybe what we've got is that we fixed the stdio\n> loss problem, and now the error rate is down to the point where we can\n> notice other, even-lower-probability issues.\nYes, in this case stderr is not missing (it's present with the error).\nSo it's really different case. As is another one:\n\ntest connect/test5                ... stderr FAILED      238 ms\n\ndiff -w -U3 .../src/interfaces/ecpg/test/expected/connect-test5.stderr\n.../src/interfaces/ecpg/test/results/connect-test5.stderr\n--- .../src/interfaces/ecpg/test/expected/connect-test5.stderr   \n2020-10-13 21:51:14 +0300\n+++ .../src/interfaces/ecpg/test/results/connect-test5.stderr   \n2020-10-18 20:59:46 +0300\n@@ -73,7 +73,9 @@\n [NO_PID]: sqlca: code: -220, state: 08003\n [NO_PID]: ECPGconnect: opening database <DEFAULT> on <DEFAULT> port\n<DEFAULT>  for user regress_ecpg_user2\n [NO_PID]: sqlca: code: 0, state: 00000\n-[NO_PID]: ECPGconnect: could not open database: FATAL:  database\n\"regress_ecpg_user2\" does not exist\n+[NO_PID]: ECPGconnect: could not open database: server closed the\nconnection unexpectedly\n+    This probably means the server terminated abnormally\n+    before or while processing the request.\n\nand the server.log:\n2020-10-18 20:59:45.731 MSK client backend[1380] ecpg/connect-test4\nLOG:  could not receive data from client: An existing connection was\nforcibly closed by the remote host.\n   \n2020-10-18 20:59:45.898 MSK client backend[2884] [unknown] FATAL: \ndatabase \"regress_ecpg_user2\" does not exist\n2020-10-18 20:59:45.992 MSK client backend[1640] [unknown] FATAL: \ndatabase \"regress_ecpg_user2\" does not exist\n\nI just wanted to inform that the ECPG-test failures can still persist in\nthe buildfarm, unfortunately.\n\nBest regards,\nAlexander\n\n\n", "msg_date": "Sun, 18 Oct 2020 21:30:01 +0300", "msg_from": "Alexander Lakhin <exclusion@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Sometimes the output to the stdout in Windows disappears" }, { "msg_contents": "Alexander Lakhin <exclusion@gmail.com> writes:\n> I've made a simple cmd script to reproduce problems seen on dory:\n> ...\n> Without the fix I've got errors on iterations 43, 46, 128, 47, 14, 4,\n> 27, which approximately corresponds to the ECPG-Check failure frequency\n> on dory (for HEAD).\n> With the fix all the 200 iterations passed as expected.\n> Then I ran the loop again just to be sure and got:\n> test thread/descriptor            ... stderr FAILED       81 ms\n> iteration 124 failed.\n\nI had been thinking we'd have to wait a month or two for the buildfarm\nto accumulate enough runs to be confident in whether the WSACleanup\nremoval fixes the ecpg failures. However, now that you did this\nexperiment, I think we have enough evidence already that it fixes it\n(or at least makes things an order of magnitude better).\n\nSo now I'm inclined to not wait, but go ahead and backpatch 7d00a6b2d\nnow. There's still enough time before the November releases that we\ncan expect that any nasty problems will show up in the buildfarm\nbefore we ship.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 18 Oct 2020 14:33:14 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Sometimes the output to the stdout in Windows disappears" }, { "msg_contents": "Alexander Lakhin <exclusion@gmail.com> writes:\n> I just wanted to inform that the ECPG-test failures can still persist in\n> the buildfarm, unfortunately.\n\nRight, but at least now we can see that there are other issues to\ninvestigate. Personally I stopped paying any attention to buildfarm\nECPG failures on Windows some time ago, figuring they were all the\nmysterious stdout-truncation problem. With that gone there'll be\nless noise and more signal in the buildfarm results.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 18 Oct 2020 14:38:14 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Sometimes the output to the stdout in Windows disappears" } ]
[ { "msg_contents": "Jaime Casanova recently reported a situation where pglogical replicating\nfrom 64 POS sites to a single central (64-core) node, each with two\nreplication sets, causes XLog's info_lck to become highly contended\nbecause of frequently reading LogwrtResult. We tested the simple fix of\nadding a new LWLock that protects LogwrtResult and LogwrtRqst; that\nseems to solve the problem easily enough.\n\nAt first I wanted to make the new LWLock cover only LogwrtResult proper,\nand leave LogwrtRqst alone. However on doing it, it seemed that that\nmight change the locking protocol in a nontrivial way. So I decided to\nmake it cover both and call it a day. We did verify that the patch\nsolves the reported problem, at any rate.\n\n-- \n�lvaro Herrera PostgreSQL Expert, https://www.2ndQuadrant.com/", "msg_date": "Mon, 31 Aug 2020 14:21:56 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "LogwrtResult contended spinlock" }, { "msg_contents": "Hi, \n\nOn August 31, 2020 11:21:56 AM PDT, Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n>Jaime Casanova recently reported a situation where pglogical\n>replicating\n>from 64 POS sites to a single central (64-core) node, each with two\n>replication sets, causes XLog's info_lck to become highly contended\n>because of frequently reading LogwrtResult. We tested the simple fix\n>of\n>adding a new LWLock that protects LogwrtResult and LogwrtRqst; that\n>seems to solve the problem easily enough.\n>\n>At first I wanted to make the new LWLock cover only LogwrtResult\n>proper,\n>and leave LogwrtRqst alone. However on doing it, it seemed that that\n>might change the locking protocol in a nontrivial way. So I decided to\n>make it cover both and call it a day. We did verify that the patch\n>solves the reported problem, at any rate.\n\nWouldn't the better fix here be to allow reading of individual members without a lock? E.g. by wrapping each in a 64bit atomic.\n\nAndres\n-- \nSent from my Android device with K-9 Mail. Please excuse my brevity.\n\n\n", "msg_date": "Mon, 31 Aug 2020 11:29:38 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On 2020-Aug-31, Andres Freund wrote:\n\n> Hi, \n> \n> On August 31, 2020 11:21:56 AM PDT, Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n\n> >At first I wanted to make the new LWLock cover only LogwrtResult\n> >proper,\n> >and leave LogwrtRqst alone. However on doing it, it seemed that that\n> >might change the locking protocol in a nontrivial way. So I decided to\n> >make it cover both and call it a day. We did verify that the patch\n> >solves the reported problem, at any rate.\n> \n> Wouldn't the better fix here be to allow reading of individual members\n> without a lock? E.g. by wrapping each in a 64bit atomic.\n\nHeh, Simon said the same. It's not clear to me due to the lack of\ngeneral availability of 64-bit atomics. If they are spinlock-protected\nwhen emulated, I think that would make the problem worse.\n\nIIRC Thomas wanted to start relying on atomic 64-bit vars in some patch,\nbut I don't remember what it was.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 31 Aug 2020 14:34:45 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Hi, \n\nOn August 31, 2020 11:34:45 AM PDT, Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n>On 2020-Aug-31, Andres Freund wrote:\n>\n>> Hi, \n>> \n>> On August 31, 2020 11:21:56 AM PDT, Alvaro Herrera\n><alvherre@2ndquadrant.com> wrote:\n>\n>> >At first I wanted to make the new LWLock cover only LogwrtResult\n>> >proper,\n>> >and leave LogwrtRqst alone. However on doing it, it seemed that\n>that\n>> >might change the locking protocol in a nontrivial way. So I decided\n>to\n>> >make it cover both and call it a day. We did verify that the patch\n>> >solves the reported problem, at any rate.\n>> \n>> Wouldn't the better fix here be to allow reading of individual\n>members\n>> without a lock? E.g. by wrapping each in a 64bit atomic.\n>\n>Heh, Simon said the same. It's not clear to me due to the lack of\n>general availability of 64-bit atomics. If they are spinlock-protected\n>when emulated, I think that would make the problem worse.\n>\n>IIRC Thomas wanted to start relying on atomic 64-bit vars in some\n>patch,\n>but I don't remember what it was.\n\nAll relevant platforms have 64bit atomics. So I don't think there's much point in worrying about the emulated performance. Correctness, sure. Performance, not so much.\n\nAndres\n-- \nSent from my Android device with K-9 Mail. Please excuse my brevity.\n\n\n", "msg_date": "Mon, 31 Aug 2020 11:38:11 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Looking at patterns like this\n\n\tif (XLogCtl->LogwrtRqst.Write < EndPos)\n\t\tXLogCtl->LogwrtRqst.Write = EndPos;\n\nIt seems possible to implement with\n\n do {\n \tXLogRecPtr\tcurrwrite;\n\n currwrite = pg_atomic_read_u64(LogwrtRqst.Write);\n\tif (currwrite > EndPos)\n break; // already done by somebody else\n if (pg_atomic_compare_exchange_u64(LogwrtRqst.Write,\n\t currwrite, EndPos))\n break; // successfully updated\n } while (true);\n\nThis assumes that LogwrtRqst.Write never goes backwards, so it doesn't\nseem good material for a general routine.\n\nThis *seems* correct to me, though this is muddy territory to me. Also,\nare there better ways to go about this?\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 3 Sep 2020 14:34:52 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Hi,\n\nOn 2020-09-03 14:34:52 -0400, Alvaro Herrera wrote:\n> Looking at patterns like this\n> \n> \tif (XLogCtl->LogwrtRqst.Write < EndPos)\n> \t\tXLogCtl->LogwrtRqst.Write = EndPos;\n> \n> It seems possible to implement with\n> \n> do {\n> \tXLogRecPtr\tcurrwrite;\n> \n> currwrite = pg_atomic_read_u64(LogwrtRqst.Write);\n> \tif (currwrite > EndPos)\n> break; // already done by somebody else\n> if (pg_atomic_compare_exchange_u64(LogwrtRqst.Write,\n> \t currwrite, EndPos))\n> break; // successfully updated\n> } while (true);\n> \n> This assumes that LogwrtRqst.Write never goes backwards, so it doesn't\n> seem good material for a general routine.\n> \n> This *seems* correct to me, though this is muddy territory to me. Also,\n> are there better ways to go about this?\n\nHm, I was thinking that we'd first go for reading it without a spinlock,\nbut continuing to write it as we currently do.\n\nBut yea, I can't see an issue with what you propose here. I personally\nfind do {} while () weird and avoid it when not explicitly useful, but\nthat's extremely minor, obviously.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 4 Sep 2020 10:05:45 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Hi,\n\nOn 2020-09-04 10:05:45 -0700, Andres Freund wrote:\n> On 2020-09-03 14:34:52 -0400, Alvaro Herrera wrote:\n> > Looking at patterns like this\n> > \n> > \tif (XLogCtl->LogwrtRqst.Write < EndPos)\n> > \t\tXLogCtl->LogwrtRqst.Write = EndPos;\n> > \n> > It seems possible to implement with\n> > \n> > do {\n> > \tXLogRecPtr\tcurrwrite;\n> > \n> > currwrite = pg_atomic_read_u64(LogwrtRqst.Write);\n> > \tif (currwrite > EndPos)\n> > break; // already done by somebody else\n> > if (pg_atomic_compare_exchange_u64(LogwrtRqst.Write,\n> > \t currwrite, EndPos))\n> > break; // successfully updated\n> > } while (true);\n> > \n> > This assumes that LogwrtRqst.Write never goes backwards, so it doesn't\n> > seem good material for a general routine.\n> > \n> > This *seems* correct to me, though this is muddy territory to me. Also,\n> > are there better ways to go about this?\n> \n> Hm, I was thinking that we'd first go for reading it without a spinlock,\n> but continuing to write it as we currently do.\n> \n> But yea, I can't see an issue with what you propose here. I personally\n> find do {} while () weird and avoid it when not explicitly useful, but\n> that's extremely minor, obviously.\n\nRe general routine: On second thought, it might actually be worth having\nit. Even just for LSNs - there's plenty places where it's useful to\nensure a variable is at least a certain size. I think I would be in\nfavor of a general helper function.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 4 Sep 2020 10:13:55 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On 04.09.2020 20:13, Andres Freund wrote:\n> Hi,\n>\n> On 2020-09-04 10:05:45 -0700, Andres Freund wrote:\n>> On 2020-09-03 14:34:52 -0400, Alvaro Herrera wrote:\n>>> Looking at patterns like this\n>>>\n>>> \tif (XLogCtl->LogwrtRqst.Write < EndPos)\n>>> \t\tXLogCtl->LogwrtRqst.Write = EndPos;\n>>>\n>>> It seems possible to implement with\n>>>\n>>> do {\n>>> \tXLogRecPtr\tcurrwrite;\n>>>\n>>> currwrite = pg_atomic_read_u64(LogwrtRqst.Write);\n>>> \tif (currwrite > EndPos)\n>>> break; // already done by somebody else\n>>> if (pg_atomic_compare_exchange_u64(LogwrtRqst.Write,\n>>> \t currwrite, EndPos))\n>>> break; // successfully updated\n>>> } while (true);\n>>>\n>>> This assumes that LogwrtRqst.Write never goes backwards, so it doesn't\n>>> seem good material for a general routine.\n>>>\n>>> This *seems* correct to me, though this is muddy territory to me. Also,\n>>> are there better ways to go about this?\n>> Hm, I was thinking that we'd first go for reading it without a spinlock,\n>> but continuing to write it as we currently do.\n>>\n>> But yea, I can't see an issue with what you propose here. I personally\n>> find do {} while () weird and avoid it when not explicitly useful, but\n>> that's extremely minor, obviously.\n> Re general routine: On second thought, it might actually be worth having\n> it. Even just for LSNs - there's plenty places where it's useful to\n> ensure a variable is at least a certain size. I think I would be in\n> favor of a general helper function.\nDo you mean by general helper function something like this?\n\nvoid\nswap_lsn(XLogRecPtr old_value, XLogRecPtr new_value, bool to_largest)\n{\n   while (true) {\n     XLogRecPtr  currwrite;\n\n     currwrite = pg_atomic_read_u64(old_value);\n\n     if (to_largest)\n       if (currwrite > new_value)\n         break;  /* already done by somebody else */\n     else\n       if (currwrite < new_value)\n         break;  /* already done by somebody else */\n\n     if (pg_atomic_compare_exchange_u64(old_value,\n                        currwrite, new_value))\n     break;  /* already done by somebody else */\n   }\n}\n\n\nwhich will be called like\nswap_lsn(XLogCtl->LogwrtRqst.Write, EndPos, true);\n\n>\n> Greetings,\n>\n> Andres Freund\n\nThis CF entry was inactive for a while. Alvaro, are you going to \ncontinue working on it?\n\n-- \nAnastasia Lubennikova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Tue, 24 Nov 2020 13:36:58 +0300", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On 2020-Nov-24, Anastasia Lubennikova wrote:\n\n> On 04.09.2020 20:13, Andres Freund wrote:\n\n> > Re general routine: On second thought, it might actually be worth having\n> > it. Even just for LSNs - there's plenty places where it's useful to\n> > ensure a variable is at least a certain size. I think I would be in\n> > favor of a general helper function.\n> Do you mean by general helper function something like this?\n> \n> void\n> swap_lsn(XLogRecPtr old_value, XLogRecPtr new_value, bool to_largest)\n\nSomething like that, yeah, though maybe name it \"pg_atomic_increase_lsn\"\nor some similar name that makes it clear that \n\n1. it is supposed to use atomics\n2. it can only be used to *advance* a value rather than a generic swap.\n\n(I'm not 100% clear that that's the exact API we need.)\n\n> This CF entry was inactive for a while. Alvaro, are you going to continue\n> working on it?\n\nYes, please move it forward. I'll post an update sometime before the\nnext CF.\n\n\n", "msg_date": "Tue, 24 Nov 2020 12:01:53 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Hi Alvaro,\n\nOn Wed, Nov 25, 2020 at 12:02 AM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n>\n> On 2020-Nov-24, Anastasia Lubennikova wrote:\n>\n> > On 04.09.2020 20:13, Andres Freund wrote:\n>\n> > > Re general routine: On second thought, it might actually be worth having\n> > > it. Even just for LSNs - there's plenty places where it's useful to\n> > > ensure a variable is at least a certain size. I think I would be in\n> > > favor of a general helper function.\n> > Do you mean by general helper function something like this?\n> >\n> > void\n> > swap_lsn(XLogRecPtr old_value, XLogRecPtr new_value, bool to_largest)\n>\n> Something like that, yeah, though maybe name it \"pg_atomic_increase_lsn\"\n> or some similar name that makes it clear that\n>\n> 1. it is supposed to use atomics\n> 2. it can only be used to *advance* a value rather than a generic swap.\n>\n> (I'm not 100% clear that that's the exact API we need.)\n>\n> > This CF entry was inactive for a while. Alvaro, are you going to continue\n> > working on it?\n>\n> Yes, please move it forward. I'll post an update sometime before the\n> next CF.\n\nAnything update on this?\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Fri, 22 Jan 2021 22:23:46 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On 2021-Jan-22, Masahiko Sawada wrote:\n\n> On Wed, Nov 25, 2020 at 12:02 AM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n\n> > Yes, please move it forward. I'll post an update sometime before the\n> > next CF.\n> \n> Anything update on this?\n\nI'll update this one early next week.\n\nThanks!\n\n-- \n�lvaro Herrera Valdivia, Chile\n\"I would rather have GNU than GNOT.\" (ccchips, lwn.net/Articles/37595/)\n\n\n", "msg_date": "Fri, 22 Jan 2021 10:39:00 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Fri, Jan 22, 2021 at 10:39 PM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n>\n> On 2021-Jan-22, Masahiko Sawada wrote:\n>\n> > On Wed, Nov 25, 2020 at 12:02 AM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n>\n> > > Yes, please move it forward. I'll post an update sometime before the\n> > > next CF.\n> >\n> > Anything update on this?\n>\n> I'll update this one early next week.\n\nGreat, thanks! I'll look at that.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Fri, 22 Jan 2021 23:28:46 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On 2020-Aug-31, Andres Freund wrote:\n\n> Wouldn't the better fix here be to allow reading of individual members without a lock? E.g. by wrapping each in a 64bit atomic.\n\nSo I've been playing with this and I'm annoyed about having two\ndatatypes to represent Write/Flush positions:\n\ntypedef struct XLogwrtRqst\n{\n\tXLogRecPtr\tWrite;\t\t\t/* last byte + 1 to write out */\n\tXLogRecPtr\tFlush;\t\t\t/* last byte + 1 to flush */\n} XLogwrtRqst;\n\ntypedef struct XLogwrtResult\n{\n\tXLogRecPtr\tWrite;\t\t\t/* last byte + 1 written out */\n\tXLogRecPtr\tFlush;\t\t\t/* last byte + 1 flushed */\n} XLogwrtResult;\n\nDon't they look, um, quite similar? I am strongly tempted to remove\nthat distinction, since it seems quite pointless, and introduce a\ndifferent one:\n\ntypedef struct XLogwrtAtomic\n{\n\tpg_atomic_uint64\tWrite;\t\t/* last byte + 1 of write position */\n\tpg_atomic_uint64\tFlush;\t\t/* last byte + 1 of flush position */\n} XLogwrtAtomic;\n\nthis one, with atomics, would be used for the XLogCtl struct members\nLogwrtRqst and LogwrtResult, and are always accessed using atomic ops.\nOn the other hand we would have\n\ntypedef struct XLogwrt\n{\n\tXLogRecPtr\tWrite;\t\t/* last byte + 1 of write position */\n\tXLogRecPtr\tFlush;\t\t/* last byte + 1 of flush position */\n} XLogwrt;\n\nto be used for the local-memory-only LogwrtResult, using normal\nassignment.\n\nNow, I do wonder if there's a point in keeping LogwrtResult as a local\nvariable at all; maybe since the ones in shared memory are going to use\nunlocked access, we don't need it anymore? I'd prefer to defer that\ndecision to after this patch is done, since ISTM that it'd merit more\ncareful benchmarking.\n\nThoughts?\n\n-- \n�lvaro Herrera Valdivia, Chile\n\n\n", "msg_date": "Fri, 29 Jan 2021 12:40:18 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "So I tried this, but -- perhaps not suprisingly -- I can't get it to\nwork properly; the synchronization fails. I suspect I need some\nbarriers, but I tried adding a few (probably some that are not really\nnecessary) and that didn't have the expected effect. Strangely, all\ntests work for me, but the pg_upgrade one in particular fails.\n\n(The attached is of course POC quality at best.)\n\nI'll have another look next week.\n\n-- \n�lvaro Herrera 39�49'30\"S 73�17'W", "msg_date": "Fri, 29 Jan 2021 22:47:56 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Hi,\n\n\nOn 2021-01-29 12:40:18 -0300, Alvaro Herrera wrote:\n> On 2020-Aug-31, Andres Freund wrote:\n> \n> > Wouldn't the better fix here be to allow reading of individual members without a lock? E.g. by wrapping each in a 64bit atomic.\n> \n> So I've been playing with this and I'm annoyed about having two\n> datatypes to represent Write/Flush positions:\n> \n> typedef struct XLogwrtRqst\n> {\n> \tXLogRecPtr\tWrite;\t\t\t/* last byte + 1 to write out */\n> \tXLogRecPtr\tFlush;\t\t\t/* last byte + 1 to flush */\n> } XLogwrtRqst;\n> \n> typedef struct XLogwrtResult\n> {\n> \tXLogRecPtr\tWrite;\t\t\t/* last byte + 1 written out */\n> \tXLogRecPtr\tFlush;\t\t\t/* last byte + 1 flushed */\n> } XLogwrtResult;\n> \n> Don't they look, um, quite similar? I am strongly tempted to remove\n> that distinction, since it seems quite pointless, and introduce a\n> different one:\n\nTheir spelling drives me nuts. Like, one is *Rqst, the other *Result?\nComeon.\n\n\n> Now, I do wonder if there's a point in keeping LogwrtResult as a local\n> variable at all; maybe since the ones in shared memory are going to use\n> unlocked access, we don't need it anymore? I'd prefer to defer that\n> decision to after this patch is done, since ISTM that it'd merit more\n> careful benchmarking.\n\nI think doing that might be a bit harmful - we update LogwrtResult\nfairly granularly in XLogWrite(). Doing that in those small steps in\nshared memory will increase the likelihood of cache misses in other\nbackends.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 29 Jan 2021 18:02:11 -0800", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Hi,\n\nOn 2021-01-29 22:47:56 -0300, Alvaro Herrera wrote:\n> So I tried this, but -- perhaps not suprisingly -- I can't get it to\n> work properly; the synchronization fails.\n\nWhat do you mean by \"synchronization fails\"?\n\n\n> Strangely, all tests work for me, but the pg_upgrade one in particular\n> fails.\n\nIt's one of the few tests using fsync=on.\n\n\n> +static inline void\n> +pg_atomic_monotonic_advance_u64(volatile pg_atomic_uint64 *ptr, uint64 target_)\n> +{\n> +#ifndef PG_HAVE_ATOMIC_U64_SIMULATION\n> +\tAssertPointerAlignment(ptr, 8);\n> +#endif\n> +\t/* FIXME is this algorithm correct if we have u64 simulation? */\n\nI don't see a problem.\n\n\n> +\twhile (true)\n> +\t{\n> +\t\tuint64\t\tcurrval;\n> +\n> +\t\tcurrval = pg_atomic_read_u64(ptr);\n> +\t\tif (currval > target_)\n> +\t\t\tbreak;\t/* already done by somebody else */\n> +\t\tif (pg_atomic_compare_exchange_u64(ptr, &currval, target_))\n> +\t\t\tbreak;\t/* successfully done */\n> +\t}\n> +}\n\nI suggest writing this as\n\n currval = pg_atomic_read_u64(ptr);\n while (currval < target_)\n {\n if (pg_atomic_compare_exchange_u64(ptr, &currval, target_))\n break;\n }\n\n> /*\n> * Inserting to WAL is protected by a small fixed number of WAL insertion\n> @@ -596,8 +599,10 @@ typedef struct XLogCtlData\n> {\n> \tXLogCtlInsert Insert;\n> \n> +\tXLogwrtAtomic LogwrtRqst;\n> +\tXLogwrtAtomic LogwrtResult;\n> +\n> \t/* Protected by info_lck: */\n> -\tXLogwrtRqst LogwrtRqst;\n\nNot sure putting these into the same cacheline is a good idea.\n\n\n> @@ -2166,12 +2163,11 @@ AdvanceXLInsertBuffer(XLogRecPtr upto, bool opportunistic)\n> \t\t\tif (opportunistic)\n> \t\t\t\tbreak;\n> \n> -\t\t\t/* Before waiting, get info_lck and update LogwrtResult */\n> -\t\t\tSpinLockAcquire(&XLogCtl->info_lck);\n> -\t\t\tif (XLogCtl->LogwrtRqst.Write < OldPageRqstPtr)\n> -\t\t\t\tXLogCtl->LogwrtRqst.Write = OldPageRqstPtr;\n> -\t\t\tLogwrtResult = XLogCtl->LogwrtResult;\n> -\t\t\tSpinLockRelease(&XLogCtl->info_lck);\n> +\t\t\t/* Before waiting, update LogwrtResult */\n> +\t\t\tpg_atomic_monotonic_advance_u64(&XLogCtl->LogwrtRqst.Write, OldPageRqstPtr);\n> +\n> +\t\t\tLogwrtResult.Write = pg_atomic_read_u64(&XLogCtl->LogwrtResult.Write);\n> +\t\t\tLogwrtResult.Flush = pg_atomic_read_u64(&XLogCtl->LogwrtResult.Flush);\n\nI don't think it's quite as easy as this. Write/Flush now aren't\nguaranteed to be coherent with each other - previously they were. And\nbecause it's in a global variable used everywhere, we can't just be more\ncareful about update protocols in one place...\n\nWe also shouldn't re-read a variable that we just did via the\npg_atomic_monotonic_advance_u64().\n\nI think we should stop updating both the Write/Flush position at the\nsame time. That way we don't have an expectation of them being coherent\nwith each other. Most places really don't need both anyway.\n\n\n> \t{\n> -\t\tSpinLockAcquire(&XLogCtl->info_lck);\n> -\t\tXLogCtl->LogwrtResult = LogwrtResult;\n> -\t\tif (XLogCtl->LogwrtRqst.Write < LogwrtResult.Write)\n> -\t\t\tXLogCtl->LogwrtRqst.Write = LogwrtResult.Write;\n> -\t\tif (XLogCtl->LogwrtRqst.Flush < LogwrtResult.Flush)\n> -\t\t\tXLogCtl->LogwrtRqst.Flush = LogwrtResult.Flush;\n> -\t\tSpinLockRelease(&XLogCtl->info_lck);\n> +\t\tpg_atomic_monotonic_advance_u64(&XLogCtl->LogwrtResult.Write, LogwrtResult.Write);\n> +\t\tpg_atomic_monotonic_advance_u64(&XLogCtl->LogwrtResult.Flush, LogwrtResult.Flush);\n> +\n> +\t\tpg_atomic_monotonic_advance_u64(&XLogCtl->LogwrtRqst.Write, LogwrtResult.Write);\n> +\t\tpg_atomic_monotonic_advance_u64(&XLogCtl->LogwrtRqst.Flush, LogwrtResult.Flush);\n\nHm. We went from one cheap atomic operation (SpinLockAcquire) to four\nexpensive ones in the happy path. That's not free...\n\nI don't think we need to manipulate XLogCtl->LogwrtResult.* using atomic\nops - they can only be updated with WALWriteLock held, right?\n\nXLogCtl->LogwrtResult was updated with plain assignment before, why did\nyou change it to pg_atomic_monotonic_advance_u64()?\n\n\n> @@ -1169,6 +1169,8 @@ XLogInsertRecord(XLogRecData *rdata,\n> \t{\n> \t\t/* advance global request to include new block(s) */\n> \t\tpg_atomic_monotonic_advance_u64(&XLogCtl->LogwrtRqst.Write, EndPos);\n> +\t\tpg_memory_barrier();\n> +\n\nThat's not really useful - the path that actually updates already\nimplies a barrier. It'd probably be better to add a barrier to a \"never\nexecuted cmpxchg\" fastpath.\n\n\n\n> @@ -2905,6 +2909,7 @@ XLogFlush(XLogRecPtr record)\n> \t\tWriteRqstPtr = pg_atomic_read_u64(&XLogCtl->LogwrtRqst.Write);\n> \t\tLogwrtResult.Write = pg_atomic_read_u64(&XLogCtl->LogwrtResult.Write);\n> \t\tLogwrtResult.Flush = pg_atomic_read_u64(&XLogCtl->LogwrtResult.Flush);\n> +\t\tpg_read_barrier();\n\nI'm not sure you really can get away with just a read barrier in these\nplaces. We can't e.g. have later updates to other shared memory\nvariables be \"moved\" to before the barrier (which a read barrier\nallows).\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 29 Jan 2021 18:30:11 -0800", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Hello,\n\nSo I addressed about half of your comments in this version merely by\nfixing silly bugs. The problem I had which I described as\n\"synchronization fails\" was one of those silly bugs.\n\nSo in further thinking, it seems simpler to make only LogwrtResult\natomic, and leave LogwrtRqst as currently, using the spinlock. This\nshould solve the contention problem we saw at the customer (but I've\nasked Jaime very nicely to do a test run, if possible, to confirm).\n\nFor things like logical replication, which call GetFlushRecPtr() very\nfrequently (causing the spinlock issue we saw) it is good, because we're\nno longer hitting the spinlock at all in that case.\n\nI have another (pretty mechanical) patch that renames LogwrtResult.Write\nto LogWriteResult and LogwrtResult.Flush to LogFlushResult. That more\nclearly shows that we're no longer updating them on unison. Didn't want\nto attach here because I didn't rebase on current one. But it seems\nlogical: there's no longer any point in doing struct assignment, which\nis the only thing that stuff was good for.\n\n\nOn 2021-Jan-29, Andres Freund wrote:\n\n> > @@ -1169,6 +1169,8 @@ XLogInsertRecord(XLogRecData *rdata,\n> > \t{\n> > \t\t/* advance global request to include new block(s)\n> > \t\t*/\n> > \t\tpg_atomic_monotonic_advance_u64(&XLogCtl->LogwrtRqst.Write, EndPos);\n> > +\t\tpg_memory_barrier();\n> \n> That's not really useful - the path that actually updates already\n> implies a barrier. It'd probably be better to add a barrier to a \"never\n> executed cmpxchg\" fastpath.\n\nGot it. Do you mean in pg_atomic_monotonic_advance_u64() itself? I'm\nnot sure which is the nicer semantics. (If it's got to be at the\ncaller, then we'll need to return a boolean from there, which sounds\nworse.)\n\n> > @@ -2905,6 +2909,7 @@ XLogFlush(XLogRecPtr record)\n> > \t\tWriteRqstPtr = pg_atomic_read_u64(&XLogCtl->LogwrtRqst.Write);\n> > \t\tLogwrtResult.Write = pg_atomic_read_u64(&XLogCtl->LogwrtResult.Write);\n> > \t\tLogwrtResult.Flush = pg_atomic_read_u64(&XLogCtl->LogwrtResult.Flush);\n> > +\t\tpg_read_barrier();\n> \n> I'm not sure you really can get away with just a read barrier in these\n> places. We can't e.g. have later updates to other shared memory\n> variables be \"moved\" to before the barrier (which a read barrier\n> allows).\n\nAh, that makes sense.\n\nI have not really studied the barrier locations terribly closely in this\nversion of the patch. It probably misses some (eg. in GetFlushRecPtr\nand GetXLogWriteRecPtr). It is passing the tests for me, but alone\nthat's probably not enough. I'm gonna try and study the generated\nassembly and see if I can make sense of things ...\n\n-- \n�lvaro Herrera 39�49'30\"S 73�17'W", "msg_date": "Tue, 2 Feb 2021 20:19:19 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Hi,\n\nOn 2021-02-02 20:19:19 -0300, Alvaro Herrera wrote:\n> > > @@ -1169,6 +1169,8 @@ XLogInsertRecord(XLogRecData *rdata,\n> > > \t{\n> > > \t\t/* advance global request to include new block(s)\n> > > \t\t*/\n> > > \t\tpg_atomic_monotonic_advance_u64(&XLogCtl->LogwrtRqst.Write, EndPos);\n> > > +\t\tpg_memory_barrier();\n> >\n> > That's not really useful - the path that actually updates already\n> > implies a barrier. It'd probably be better to add a barrier to a \"never\n> > executed cmpxchg\" fastpath.\n>\n> Got it. Do you mean in pg_atomic_monotonic_advance_u64() itself?\n\nYes.\n\n\n> I'm not sure which is the nicer semantics. (If it's got to be at the\n> caller, then we'll need to return a boolean from there, which sounds\n> worse.)\n\nNearly all other modifying atomic operations have full barrier\nsemantics, so I think it'd be better to have it inside the\npg_atomic_monotonic_advance_u64().\n\n\n> +/*\n> + * Monotonically advance the given variable using only atomic operations until\n> + * it's at least the target value.\n> + */\n> +static inline void\n> +pg_atomic_monotonic_advance_u64(volatile pg_atomic_uint64 *ptr, uint64 target_)\n> +{\n> +\tuint64\t\tcurrval;\n> +\n> +#ifndef PG_HAVE_ATOMIC_U64_SIMULATION\n> +\tAssertPointerAlignment(ptr, 8);\n> +#endif\n> +\n> +\tcurrval = pg_atomic_read_u64(ptr);\n> +\twhile (currval < target_)\n> +\t{\n> +\t\tif (pg_atomic_compare_exchange_u64(ptr, &currval, target_))\n> +\t\t\tbreak;\n> +\t}\n> +}\n\nSo I think it'd be\n\nstatic inline void\npg_atomic_monotonic_advance_u64(volatile pg_atomic_uint64 *ptr, uint64 target_)\n{\n uint64 currval;\n\n#ifndef PG_HAVE_ATOMIC_U64_SIMULATION\n AssertPointerAlignment(ptr, 8);\n#endif\n\n currval = pg_atomic_read_u64(ptr);\n if (currval >= target_)\n {\n pg_memory_barrier();\n return;\n }\n\n while (currval < target_)\n {\n if (pg_atomic_compare_exchange_u64(ptr, &currval, target_))\n break;\n }\n}\n\n\n> @@ -1172,9 +1170,10 @@ XLogInsertRecord(XLogRecData *rdata,\n> \t\t/* advance global request to include new block(s) */\n> \t\tif (XLogCtl->LogwrtRqst.Write < EndPos)\n> \t\t\tXLogCtl->LogwrtRqst.Write = EndPos;\n> -\t\t/* update local result copy while I have the chance */\n> -\t\tLogwrtResult = XLogCtl->LogwrtResult;\n> \t\tSpinLockRelease(&XLogCtl->info_lck);\n> +\t\t/* update local result copy */\n> +\t\tLogwrtResult.Write = pg_atomic_read_u64(&XLogCtl->LogwrtResult.Write);\n> +\t\tLogwrtResult.Flush = pg_atomic_read_u64(&XLogCtl->LogwrtResult.Flush);\n> \t}\n\nAs mentioned before - it's not clear to me why this is a valid thing to\ndo without verifying all LogwrtResult.* usages. You can get updates\ncompletely out of order / independently.\n\n\n> @@ -2675,8 +2673,10 @@ XLogWrite(XLogwrtRqst WriteRqst, bool flexible)\n> \t * code in a couple of places.\n> \t */\n> \t{\n> +\t\tpg_atomic_monotonic_advance_u64(&XLogCtl->LogwrtResult.Write, LogwrtResult.Write);\n> +\t\tpg_atomic_monotonic_advance_u64(&XLogCtl->LogwrtResult.Flush, LogwrtResult.Flush);\n> +\t\tpg_memory_barrier();\n> \t\tSpinLockAcquire(&XLogCtl->info_lck);\n> -\t\tXLogCtl->LogwrtResult = LogwrtResult;\n\nI still don't see why we need \"locked\" atomic operations here, rather\nthan just a pg_atomic_write_u64(). They can only be modified\nwith WALWriteLock held. There's two reasons for using a spinlock in\nthis place:\n1) it avoids torn reads of 64bit values -\n pg_atomic_write_u64()/pg_atomic_read_u64() avoid that already.\n2) it ensures that Write/Flush are updated in unison - but that's not\n useful anymore, given that other places now read the variables\n separately.\n\n\n> @@ -3064,8 +3063,10 @@ XLogBackgroundFlush(void)\n> \tWriteRqst.Write -= WriteRqst.Write % XLOG_BLCKSZ;\n>\n> \t/* if we have already flushed that far, consider async commit records */\n> +\tLogwrtResult.Flush = pg_atomic_read_u64(&XLogCtl->LogwrtResult.Flush);\n> \tif (WriteRqst.Write <= LogwrtResult.Flush)\n> \t{\n> +\t\tpg_memory_barrier();\n> \t\tSpinLockAcquire(&XLogCtl->info_lck);\n> \t\tWriteRqst.Write = XLogCtl->asyncXactLSN;\n> \t\tSpinLockRelease(&XLogCtl->info_lck);\n\nA SpinLockAcquire() is a full memory barrier on its own I think. This'd\nprobably better solved by just making asyncXactLSN atomic...\n\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 2 Feb 2021 16:32:50 -0800", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Tue, Feb 02, 2021 at 08:19:19PM -0300, Alvaro Herrera wrote:\n> Hello,\n> \n> So I addressed about half of your comments in this version merely by\n> fixing silly bugs. The problem I had which I described as\n> \"synchronization fails\" was one of those silly bugs.\n> \n\nHi �lvaro,\n\nAre we waiting for another version of the patch based on Andres'\ncomments? Or this version is good enough for testing?\n\nBTW, current patch still applies cleanly.\n\nregards,\n\n-- \nJaime Casanova\nDirector de Servicios Profesionales\nSystemGuards - Consultores de PostgreSQL\n\n\n", "msg_date": "Wed, 8 Sep 2021 10:14:55 -0500", "msg_from": "Jaime Casanova <jcasanov@systemguards.com.ec>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "> On 8 Sep 2021, at 17:14, Jaime Casanova <jcasanov@systemguards.com.ec> wrote:\n> \n> On Tue, Feb 02, 2021 at 08:19:19PM -0300, Alvaro Herrera wrote:\n>> Hello,\n>> \n>> So I addressed about half of your comments in this version merely by\n>> fixing silly bugs. The problem I had which I described as\n>> \"synchronization fails\" was one of those silly bugs.\n>> \n> \n> Hi Álvaro,\n> \n> Are we waiting for another version of the patch based on Andres'\n> comments? Or this version is good enough for testing?\n\nAny update on this? Should the patch be reset back to \"Needs review\" or will\nthere be a new version?\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Thu, 4 Nov 2021 13:12:13 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Here's a further attempt at this. Sorry it took so long.\nIn this version, I replaced the coupled-in-a-struct representation of\nWrite&Flush with two separate global variables. The reason to do this\nis to cater to Andres' idea to keep them up-to-date separately. Of\ncourse, I could kept them together, but it seems more sensible this way.\n\nAndres also suggested to not use monotonic-advance in XLogWrite, because\nthese update are always done with WALWriteLock held in exclusive mode.\nHowever, that doesn't work (and tests fail pretty quickly) because\nXLogWrite seems to be called possibly out of order, so you still have to\ncheck if the current value is newer than what you have to write anyway;\nusing stock atomic write doesn't work.\n\nSo this is v4.\n\n-- \nÁlvaro Herrera 39°49'30\"S 73°17'W — https://www.EnterpriseDB.com/", "msg_date": "Thu, 18 Nov 2021 19:15:58 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "There was an earlier comment by Andres that asyncXactLSN should also be\natomic, to avoid an ugly spinlock interaction with the new atomic-based\nlogwrtResult. The 0002 here is an attempt at doing that; I found that\nit also needed to change WalWriterSleeping to use atomics, to avoid\nXLogSetAsyncXactLSN having to grab the spinlock for that.\n\n\n-- \nÁlvaro Herrera Valdivia, Chile — https://www.EnterpriseDB.com/\n\"Learn about compilers. Then everything looks like either a compiler or\na database, and now you have two problems but one of them is fun.\"\n https://twitter.com/thingskatedid/status/1456027786158776329", "msg_date": "Mon, 22 Nov 2021 18:56:43 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Hi,\n\nOn 2021-11-22 18:56:43 -0300, Alvaro Herrera wrote:\n> There was an earlier comment by Andres that asyncXactLSN should also be\n> atomic, to avoid an ugly spinlock interaction with the new atomic-based\n> logwrtResult. The 0002 here is an attempt at doing that; I found that\n> it also needed to change WalWriterSleeping to use atomics, to avoid\n> XLogSetAsyncXactLSN having to grab the spinlock for that.\n\nThis patch currently doesn't apply: http://cfbot.cputube.org/patch_37_2716.log\n\nAre you aiming this for v15? Otherwise I'd like to move the entry to the next\nCF. Marked as waiting-on-author.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 21 Mar 2022 18:11:18 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On 2022-Mar-21, Andres Freund wrote:\n\n> This patch currently doesn't apply: http://cfbot.cputube.org/patch_37_2716.log\n\nUpdated.\n\n> Are you aiming this for v15? Otherwise I'd like to move the entry to the next\n> CF. Marked as waiting-on-author.\n\nI'd like to get 0001 pushed to pg15, yes. I'll let 0002 sit here for\ndiscussion, but I haven't seen any evidence that we need it. If others\nvouch for it, I can push that one too, but I'd rather have it be a\nseparate thing.\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/\n\"El miedo atento y previsor es la madre de la seguridad\" (E. Burke)", "msg_date": "Tue, 22 Mar 2022 14:49:13 +0100", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Alvaro Herrera <alvherre@alvh.no-ip.org> writes:\n> On 2022-Mar-21, Andres Freund wrote:\n>> Are you aiming this for v15? Otherwise I'd like to move the entry to the next\n>> CF. Marked as waiting-on-author.\n\n> I'd like to get 0001 pushed to pg15, yes. I'll let 0002 sit here for\n> discussion, but I haven't seen any evidence that we need it. If others\n> vouch for it, I can push that one too, but I'd rather have it be a\n> separate thing.\n\nI looked briefly at 0001, and I've got to say that I disagree with\nyour decision to rearrange the representation of the local LogwrtResult\ncopy. It clutters the patch tremendously and makes it hard to\nunderstand what the actual functional change is. Moreover, I'm\nnot entirely convinced that it's a notational improvement in the\nfirst place.\n\nPerhaps it'd help if you split 0001 into two steps, one to do the\nmechanical change of the representation and then a second patch that\nconverts the shared variable to atomics. Since you've moved around\nthe places that read the shared variable, that part is subtler than\none could wish and really needs to be studied on its own.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 22 Mar 2022 09:59:16 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On 2022-Mar-22, Tom Lane wrote:\n\n> I looked briefly at 0001, and I've got to say that I disagree with\n> your decision to rearrange the representation of the local LogwrtResult\n> copy. It clutters the patch tremendously and makes it hard to\n> understand what the actual functional change is. Moreover, I'm\n> not entirely convinced that it's a notational improvement in the\n> first place.\n> \n> Perhaps it'd help if you split 0001 into two steps, one to do the\n> mechanical change of the representation and then a second patch that\n> converts the shared variable to atomics. Since you've moved around\n> the places that read the shared variable, that part is subtler than\n> one could wish and really needs to be studied on its own.\n\nHmm, I did it the other way around: first change to use atomics, then\nthe mechanical change. I think that makes the usefulness of the change\nmore visible, because before the atomics use the use of the combined\nstruct as a unit remains sensible.\n\n-- \nÁlvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/\nOfficer Krupke, what are we to do?\nGee, officer Krupke, Krup you! (West Side Story, \"Gee, Officer Krupke\")", "msg_date": "Tue, 22 Mar 2022 17:11:20 +0100", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "So I've been wondering about this block at the bottom of XLogWrite:\n\n\t/*\n\t * Make sure that the shared 'request' values do not fall behind the\n\t * 'result' values. This is not absolutely essential, but it saves some\n\t * code in a couple of places.\n\t */\n\t{\n\t\tSpinLockAcquire(&XLogCtl->info_lck);\n\t\tif (XLogCtl->LogwrtRqst.Write < LogwrtResult.Write)\n\t\t\tXLogCtl->LogwrtRqst.Write = LogwrtResult.Write;\n\t\tif (XLogCtl->LogwrtRqst.Flush < LogwrtResult.Flush)\n\t\t\tXLogCtl->LogwrtRqst.Flush = LogwrtResult.Flush;\n\t\tSpinLockRelease(&XLogCtl->info_lck);\n\t}\n\nI just noticed that my 0001 makes the comment a lie: it is now quite\npossible that 'result' is advanced beyond 'request'. Before the patch\nthat never happened because they were both advanced in the region locked\nby the spinlock.\n\nI think we could still maintain this promise if we just moved this\nentire block before the first pg_atomic_monotonic_advance_u64 setting\nXLogCtl->LogwrtResult.Write. Or we could halve the whole block, and put\none acquire/test/set/release stanza before each monotonic increase of\nthe corresponding variable.\n\n\nHowever, I wonder if this is still necessary. This code was added in\n4d14fe0048c (March 2001) and while everything else was quite different\nback then, this hasn't changed at all. I can't quite figure out what\nare those \"couple of places\" that would need additional code if this\nblock is just removed. I tried running the tests (including\nwal_consistency_checking), and nothing breaks. Reading the code\nsurrounding the other accesses of XLogCtl->LogwrtRqst, there's nothing\nthat looks to me like it depends on these values not lagging behind\nLogwrtResult.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"If you have nothing to say, maybe you need just the right tool to help you\nnot say it.\" (New York Times, about Microsoft PowerPoint)\n\n\n", "msg_date": "Tue, 22 Mar 2022 19:58:34 +0100", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Here's a v8, where per my previous comment I removed some code that I\nbelieve is no longer necessary.\n\nI've omitted the patch that renames LogwrtResult subvariables into\nLogWriteResult/LogWriteFlush; I still think the end result is better\nafter that one, but it's a pretty trivial change that can be dealt with\nseparately afterwards.\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/\n\"Saca el libro que tu religión considere como el indicado para encontrar la\noración que traiga paz a tu alma. Luego rebootea el computador\ny ve si funciona\" (Carlos Duclós)", "msg_date": "Tue, 5 Apr 2022 17:47:04 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Apologies -- I selected the wrong commit to extract the commit message\nfrom. Here it is again. I also removed an obsolete /* XXX */ comment.\n\n-- \nÁlvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/", "msg_date": "Tue, 5 Apr 2022 20:16:28 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On 2022-Apr-05, Alvaro Herrera wrote:\n\n> Apologies -- I selected the wrong commit to extract the commit message\n> from. Here it is again. I also removed an obsolete /* XXX */ comment.\n\nI spent a lot of time staring at this to understand the needs for memory\nbarriers in the interactions. In the end I decided not to get this out\nfor this cycle because I don't want to create subtle bugs in WAL. I'll\ncome back with this for pg16.\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/\n\"El que vive para el futuro es un iluso, y el que vive para el pasado,\nun imbécil\" (Luis Adler, \"Los tripulantes de la noche\")\n\n\n", "msg_date": "Thu, 7 Apr 2022 20:29:44 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "v10 is just a trivial rebase. No changes. Moved to next commitfest.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/", "msg_date": "Thu, 28 Jul 2022 08:59:20 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On 2022-Jul-28, Alvaro Herrera wrote:\n\n> v10 is just a trivial rebase. No changes. Moved to next commitfest.\n\nI realized that because of commit e369f3708636 this change is no longer\nas critical as it used to be, so I'm withdrawing this patch from the\ncommitfest.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"No necesitamos banderas\n No reconocemos fronteras\" (Jorge González)\n\n\n", "msg_date": "Fri, 23 Sep 2022 10:49:41 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Fri, 2022-09-23 at 10:49 +0200, Alvaro Herrera wrote:\n> On 2022-Jul-28, Alvaro Herrera wrote:\n> \n> > v10 is just a trivial rebase.  No changes.  Moved to next\n> > commitfest.\n> \n> I realized that because of commit e369f3708636 this change is no\n> longer\n> as critical as it used to be, so I'm withdrawing this patch from the\n> commitfest.\n\nIt looks like there's some renewed interest in this patch:\n\nhttps://www.postgresql.org/message-id/20240213001150.4uqzh7tinuhvoopl@awork3.anarazel.de\n\neven if there's not a pressing performance conern now, it could clean\nup the complexity of having a non-shared copy of LogwrtResult.\n\nRegards,\n\tJeff Davis\n\n\n\n", "msg_date": "Mon, 12 Feb 2024 17:44:33 -0800", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Mon, 2024-02-12 at 17:44 -0800, Jeff Davis wrote:\n> It looks like there's some renewed interest in this patch:\n\nAfter rebasing (attached as 0001), I'm seeing some test failures. It\nlooks like the local LogwrtResult is not being updated in as many\nplaces, and that's hitting the Assert that I recently added. The fix is\neasy (attached as 0002).\n\nThough it looks like we can remove the non-shared LogwrtResult\nentirely. Andres expressed some concern here:\n\nhttps://www.postgresql.org/message-id/20210130020211.rtu5ir3dpjrbiats@alap3.anarazel.de\n\nBut then seemed to favor removing it here:\n\nhttps://www.postgresql.org/message-id/20240213001150.4uqzh7tinuhvoopl@awork3.anarazel.de\n\nI'm inclined to think we can get rid of the non-shared copy.\n\nA few other comments:\n\n * Should GetFlushRecPtr()/GetXLogWriteRecPtr() use a read memory\nbarrier?\n * Why did you add pg_memory_barrier() right before a spinlock\nacquisition?\n * Is it an invariant that Write >= Flush at all times? Are there\nguaranteed to be write barriers in the right place to ensure that?\n\nI would also like it if we could add a new \"Copy\" pointer indicating\nhow much WAL data has been copied to the WAL buffers. That would be set\nby WaitXLogInsertionsToFinish() so that subsequent calls are cheap.\nAttached a patch (0003) for illustration purposes. It adds to the size\nof XLogCtlData, but it's fairly large already, so I'm not sure if\nthat's a problem. If we do add this, there would be an invariant that\nCopy >= Write at all times.\n\nRegards,\n\tJeff Davis", "msg_date": "Fri, 16 Feb 2024 12:54:25 -0800", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Sat, Feb 17, 2024 at 2:24 AM Jeff Davis <pgsql@j-davis.com> wrote:\n>\n> Though it looks like we can remove the non-shared LogwrtResult\n> entirely. Andres expressed some concern here:\n>\n> https://www.postgresql.org/message-id/20210130020211.rtu5ir3dpjrbiats@alap3.anarazel.de\n>\n> But then seemed to favor removing it here:\n>\n> https://www.postgresql.org/message-id/20240213001150.4uqzh7tinuhvoopl@awork3.anarazel.de\n>\n> I'm inclined to think we can get rid of the non-shared copy.\n\nThe local copy of LogwrtResult is so frequently used in the backends,\nif we were to replace it with atomic accesses, won't the atomic reads\nbe costly and start showing up in perf profiles? In any case, I prefer\ndiscussing this separately once we get to a conclusion on converting\nshared memory Write and Flush ptrs to atomics.\n\n> A few other comments:\n>\n> * Should GetFlushRecPtr()/GetXLogWriteRecPtr() use a read memory\n> barrier?\n> * Why did you add pg_memory_barrier() right before a spinlock\n> acquisition?\n> * Is it an invariant that Write >= Flush at all times? Are there\n> guaranteed to be write barriers in the right place to ensure that?\n\nI'll continue to think about these points.\n\n> I would also like it if we could add a new \"Copy\" pointer indicating\n> how much WAL data has been copied to the WAL buffers. That would be set\n> by WaitXLogInsertionsToFinish() so that subsequent calls are cheap.\n> Attached a patch (0003) for illustration purposes. It adds to the size\n> of XLogCtlData, but it's fairly large already, so I'm not sure if\n> that's a problem. If we do add this, there would be an invariant that\n> Copy >= Write at all times.\n\nThanks. I have a few comments on v11j patches.\n\n1. I guess we need to initialize the new atomics with\npg_atomic_init_u64 initially in XLOGShmemInit:\n\n2. I guess we need to update both the Write and Flush local copies in\nAdvanceXLInsertBuffer. Overall, I guess we need to update both the\nWrite and Flush local copies whenever we previously read LogwrtResult,\nno? Missing to do that caused regression tests to fail and since we\nwere able to catch it, we ended up with v11j-0002-fixup.patch. There\nmight be cases where we aren't able to catch if we didn't update both\nWrite and Flush local copies. I'd suggest we just wrap both of these\nunder a macro:\n\n LogwrtResult.Flush = pg_atomic_read_u64(&XLogCtl->LogwrtResult.Flush);\n LogwrtResult.Write = pg_atomic_read_u64(&XLogCtl->LogwrtResult.Write);\n\nand just use it wherever we did LogwrtResult = XLogCtl->LogwrtResult;\npreviously but not under spinlock.\n\n3.\n@@ -6371,7 +6373,9 @@ GetFlushRecPtr(TimeLineID *insertTLI)\n {\n Assert(XLogCtl->SharedRecoveryState == RECOVERY_STATE_DONE);\n\n+ pg_read_barrier();\n LogwrtResult.Flush = pg_atomic_read_u64(&XLogCtl->LogwrtResult.Flush);\n+ LogwrtResult.Write = pg_atomic_read_u64(&XLogCtl->LogwrtResult.Write);\n\nDo we need a read barrier here to not reorder things when more than\none process is accessing the flush and write ptrs? If at all, a read\nbarrier is warranted here, we can use atomic read with full barrier\nsematices as proposed here (when that's in) -\nhttps://www.postgresql.org/message-id/20231127210030.GA140335%40nathanxps13.\n\n4.\n+ /*\n+ * Update local and shared status. This is OK to do without any locks\n+ * because no other process can be reading or writing WAL yet.\n+ */\n LogwrtResult.Write = LogwrtResult.Flush = EndOfLog;\n\n+ pg_atomic_write_u64(&XLogCtl->LogwrtResult.Write, EndOfLog);\n+ pg_atomic_write_u64(&XLogCtl->LogwrtResult.Flush, EndOfLog);\n XLogCtl->LogwrtRqst.Write = EndOfLog;\n\npg_atomic_write_u64 here seems fine to me as no other process is\nactive writing WAL yet, otherwise, we need write with full barrier\nsomething like pg_write_barrier + pg_atomic_write_u64 or\npg_atomic_exchange_u64 like in LWLockUpdateVar or use atomic write\nwith full barrier sematices as proposed here (when that's in) -\nhttps://www.postgresql.org/message-id/20231127210030.GA140335%40nathanxps13.\n\n5. I guess we'd better use pg_atomic_read_u64_impl and\npg_atomic_compare_exchange_u64_impl in pg_atomic_monotonic_advance_u64\nto reduce one level of function indirections. Of course, we need the\npointer alignments that pg_atomic_compare_exchange_u64 in the new\nmonotonic function.\n\n6.\n+ * Full barrier semantics (even when value is unchanged).\n\n+ currval = pg_atomic_read_u64(ptr);\n+ if (currval >= target_)\n+ {\n+ pg_memory_barrier();\n\nPerhaps, we can use atomic read with full barrier sematices proposed\nhere - https://www.postgresql.org/message-id/20231127210030.GA140335%40nathanxps13\n\n7.\n+static inline void\n+pg_atomic_monotonic_advance_u64(volatile pg_atomic_uint64 *ptr, uint64 target_)\n\nJust for the sake of completeness, do we need\npg_atomic_monotonic_advance_u32 as well?\n\n8. I'd split the addition of these new monotonic functions into 0001,\nthen 0002 adding XLogwrtAtomic and 0003 adding Copy to XLogwrtAtomic.\n\n9.\n+ copyptr = pg_atomic_read_u64(&XLogCtl->LogwrtResult.Copy);\n+ if (startptr + count > copyptr)\n+ ereport(WARNING,\n+ (errmsg(\"request to read past end of generated WAL;\nrequest %X/%X, current position %X/%X\",\n+ LSN_FORMAT_ARGS(startptr + count),\nLSN_FORMAT_ARGS(copyptr))));\n\nAny specific reason for this to be a WARNING rather than an ERROR?\n\nI've addressed some of my review comments (#1, #5, #7 and #8) above,\nmerged the v11j-0002-fixup.patch into 0002, ran pgindent. Please see\nthe attached v12 patch set. FWIW, CF bot is happy with these patches\nand also tests with --enable-atomics=no are clean.\n\nBTW, I couldn't find a CF entry for this, so I've registered one -\nhttps://commitfest.postgresql.org/47/4846/.\n\n--\nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com", "msg_date": "Wed, 21 Feb 2024 20:00:00 +0530", "msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Wed, 2024-02-21 at 20:00 +0530, Bharath Rupireddy wrote:\n> The local copy of LogwrtResult is so frequently used in the backends,\n> if we were to replace it with atomic accesses, won't the atomic reads\n> be costly and start showing up in perf profiles?\n\nI don't see exactly where the extra cost would come from. What is your\nconcern?\n\nIn functions that access it several times, it may make sense to copy it\nto a function-local variable, of course. But having a global non-shared\nLogwrtResult doesn't seem particularly useful to me.\n\n> In any case, I prefer\n> discussing this separately once we get to a conclusion on converting\n> shared memory Write and Flush ptrs to atomics.\n\nI agree that it shouldn't block the earlier patches, but it seems on-\ntopic for this thread.\n\n> \n> 1. I guess we need to initialize the new atomics with\n> pg_atomic_init_u64 initially in XLOGShmemInit:\n\nThank you.\n\n> 2. I guess we need to update both the Write and Flush local copies in\n> AdvanceXLInsertBuffer.\n\nI agree. Whenever we update the non-shared LogwrtResult, let's update\nthe whole thing. Otherwise it's confusing.\n\n> 3.\n> @@ -6371,7 +6373,9 @@ GetFlushRecPtr(TimeLineID *insertTLI)\n>  {\n>      Assert(XLogCtl->SharedRecoveryState == RECOVERY_STATE_DONE);\n> \n> +    pg_read_barrier();\n>      LogwrtResult.Flush = pg_atomic_read_u64(&XLogCtl-\n> >LogwrtResult.Flush);\n> +    LogwrtResult.Write = pg_atomic_read_u64(&XLogCtl-\n> >LogwrtResult.Write);\n> \n> Do we need a read barrier here to not reorder things when more than\n> one process is accessing the flush and write ptrs?\n\nThe above seems wrong: we don't want to reorder a load of Write before\na load of Flush, otherwise it could look like Write < Flush.\n(Similarly, we never want to reorder a store of Flush before a store of\nWrite.) So I think we should have another read barrier between those\ntwo atomic reads.\n\nI also think we need the read barrier at the beginning because the\ncaller doesn't expect a stale value of the Flush pointer. It might not\nbe strictly required for correctness, because I don't think that stale\nvalue can be inconsistent with anything else, but getting an up-to-date\nvalue is better.\n\n> If at all, a read\n> barrier is warranted here, we can use atomic read with full barrier\n\nI don't think we need a full barrier but I'm fine with using\npg_atomic_read_membarrier_u64() if it's better for whatever reason.\n\n\n> +    pg_atomic_write_u64(&XLogCtl->LogwrtResult.Write, EndOfLog);\n> +    pg_atomic_write_u64(&XLogCtl->LogwrtResult.Flush, EndOfLog);\n>      XLogCtl->LogwrtRqst.Write = EndOfLog;\n> \n> pg_atomic_write_u64 here seems fine to me as no other process is\n> active writing WAL yet, otherwise, we need write with full barrier\n\nI don't see any memory ordering hazard. In any case, there's an\nLWLockAcquire a few lines later, which acts as a full barrier.\n\n> something like pg_write_barrier + pg_atomic_write_u64 or\n> pg_atomic_exchange_u64 like in LWLockUpdateVar or use atomic write\n> with full barrier sematices as proposed here (when that's in) -\n> https://www.postgresql.org/message-id/20231127210030.GA140335%40nathanxps13\n> .\n> \n> 5. I guess we'd better use pg_atomic_read_u64_impl and\n> pg_atomic_compare_exchange_u64_impl in\n> pg_atomic_monotonic_advance_u64\n> to reduce one level of function indirections.\n\nAren't they inlined?\n\n> 6.\n> + * Full barrier semantics (even when value is unchanged).\n> \n> +    currval = pg_atomic_read_u64(ptr);\n> +    if (currval >= target_)\n> +    {\n> +        pg_memory_barrier();\n> \n> Perhaps, we can use atomic read with full barrier sematices proposed\n> here -\n> https://www.postgresql.org/message-id/20231127210030.GA140335%40nathanxps13\n\nI don't think they are exactly equivalent: in the current patch, the\nfirst pg_atomic_read_u64() could be reordered with earlier reads;\nwhereas that wouldn't work if using pg_atomic_read_membarrier_u64() it\ncould not be. I'm not sure whether that could create a performance\nproblem or not.\n\n> Just for the sake of completeness, do we need\n> pg_atomic_monotonic_advance_u32 as well?\n\n+1.\n\n> 8. I'd split the addition of these new monotonic functions into 0001,\n> then 0002 adding XLogwrtAtomic and 0003 adding Copy to XLogwrtAtomic.\n\n+1\n\n> 9.\n> +    copyptr = pg_atomic_read_u64(&XLogCtl->LogwrtResult.Copy);\n> +    if (startptr + count > copyptr)\n> +        ereport(WARNING,\n> +                (errmsg(\"request to read past end of generated WAL;\n> request %X/%X, current position %X/%X\",\n> +                        LSN_FORMAT_ARGS(startptr + count),\n> LSN_FORMAT_ARGS(copyptr))));\n> \n> Any specific reason for this to be a WARNING rather than an ERROR?\n\nGood question. WaitXLogInsertionsToFinish() uses a LOG level message\nfor the same situation. They should probably be the same log level, and\nI would think it would be either PANIC or WARNING. I have no idea why\nLOG was chosen.\n\n> I've addressed some of my review comments (#1, #5, #7 and #8) above,\n> merged the v11j-0002-fixup.patch into 0002, ran pgindent. Please see\n> the attached v12 patch set. FWIW, CF bot is happy with these patches\n> and also tests with --enable-atomics=no are clean.\n> \n> BTW, I couldn't find a CF entry for this, so I've registered one -\n> https://commitfest.postgresql.org/47/4846/.\n\nThank you.\n\n0001:\n\n* The comments on the two versions of the functions are redundant, and\nthe style in that header seems to be to omit the comment from the u64\nversion. \n\n* I'm not sure the AssertPointerAlignment is needed in the u32 version?\n\n0002:\n\n* All updates to the non-shared LogwrtResult should update both values.\nIt's confusing to update those local values independently, because it\nviolates the invariant that LogwrtResult.Flush <= LogwrtResult.Write.\n\n* pg_memory_barrier() is not needed right before a spinlock\n\n* As mentioned above, I think GetFlushRecPtr() needs two read barriers.\nAlso, I think the same for GetXLogWriteRecPtr().\n\n* In general, for any place using both Write and Flush, I think Flush\nshould be loaded first, followed by a read barrier, followed by a load\nof the Write pointer. And I think in most of those places there should\nbe a read barrier before the load of Flush, too, to avoid a stale value\nin places that might matter.\n\n0003:\n\n* We need to maintain the invariant that Copy >= Write >= Flush. I\nbelieve that's always satisfied, because the\nXLogWaitInsertionsToFinish() is always called before XLogWrite(). But\nwe should add an assert or runtime check of this invariant somewhere.\n\n\nAlvaro, do you intend to review and/or commit this work eventually? If\nyou've set it down, I can take it. There are still a few details so I'm\nnot sure it's ready for commit quite yet, but it's getting closer.\n\nRegards,\n\tJeff Davis\n\n\n\n", "msg_date": "Wed, 21 Feb 2024 12:24:42 -0800", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Thu, Feb 22, 2024 at 1:54 AM Jeff Davis <pgsql@j-davis.com> wrote:\n> On Wed, 2024-02-21 at 20:00 +0530, Bharath Rupireddy wrote:\n> > The local copy of LogwrtResult is so frequently used in the backends,\n> > if we were to replace it with atomic accesses, won't the atomic reads\n> > be costly and start showing up in perf profiles?\n>\n> I don't see exactly where the extra cost would come from. What is your\n> concern?\n>\n> In functions that access it several times, it may make sense to copy it\n> to a function-local variable, of course. But having a global non-shared\n> LogwrtResult doesn't seem particularly useful to me.\n\nI would love to get rid of the global variable; all of our code relies\ntoo much on global variables, but the xlog code is some of the worst.\nThe logic is complex and difficult to reason about.\n\nBut I do think that there's room for concern about performance, too. I\ndon't know if there is an actual problem, but there could be a\nproblem. My impression is that accessing shared memory isn't\nintrinsically more costly than accessing backend-private memory, but\naccessing heavily contended memory can definitely be more expensive\nthan accessing uncontended memory -- and not just slightly more\nexpensive, but WAY more expensive.\n\nI think the problems tend to be worst when you have some bit of data\nthat's being frequently modified by multiple backends. Every backend\nthat wants to modify the value needs to steal the cache line, and\neventually you spend most of your CPU time stealing cache lines from\nother sockets and not much of it doing any actual work. If you have a\nvalue that's just being read by a lot of backends without\nmodification, I think the cache line can be shared in read only mode\nby all the CPUs and it's not too bad.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 22 Feb 2024 10:17:12 +0530", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Thu, 2024-02-22 at 10:17 +0530, Robert Haas wrote:\n> I think the problems tend to be worst when you have some bit of data\n> that's being frequently modified by multiple backends. Every backend\n> that wants to modify the value needs to steal the cache line, and\n> eventually you spend most of your CPU time stealing cache lines from\n> other sockets and not much of it doing any actual work. If you have a\n> value that's just being read by a lot of backends without\n> modification, I think the cache line can be shared in read only mode\n> by all the CPUs and it's not too bad.\n\nThat makes sense. I guess they'd be on the same cache line as well,\nwhich means a write to either will invalidate both.\n\nSome places (XLogWrite, XLogInsertRecord, XLogSetAsyncXactLSN,\nGetFlushRecPtr, GetXLogWriteRecPtr) already update it from shared\nmemory anyway, so those are non-issues.\n\nThe potential problem areas (unless I missed something) are:\n\n * AdvanceXLInsertBuffer reads it as an early check to see if a buffer\nis already written out.\n\n * XLogFlush / XLogNeedsFlush use it for an early return\n\n * WALReadFromBuffers reads it for an error check (currently an\nAssert, but we might want to make that an elog).\n\n * We are discussing adding a Copy pointer, which would be advanced by\nWaitXLogInsertionsToFinish(), and if we do replication-before-flush, we\nmay want to be more eager about advancing it. That could cause an\nissue, as well.\n\nI don't see the global non-shared variable as a huge problem, so if it\nserves a purpose then I'm fine keeping it. Perhaps we could make it a\nbit safer by using some wrapper functions. Something like:\n\n bool\n IsWriteRecPtrAtLeast(XLogRecPtr recptr)\n {\n XLogRecPtr writeptr;\n if (LogwrtResult.Write >= recptr)\n return true;\n writeptr = GetXLogWriteRecPtr();\n return (writeptr >= recptr);\n }\n\nThat would reduce the number of direct references to LogwrtResult,\ncallers would never see a stale value, and would avoid the cache miss\nproblem that you're concerned about. Not sure if they'd need to be\ninline or not.\n\nRegards,\n\tJeff Davis\n\n\n\n", "msg_date": "Thu, 22 Feb 2024 11:48:22 -0800", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Fri, Feb 23, 2024 at 1:18 AM Jeff Davis <pgsql@j-davis.com> wrote:\n> I don't see the global non-shared variable as a huge problem, so if it\n> serves a purpose then I'm fine keeping it. Perhaps we could make it a\n> bit safer by using some wrapper functions.\n\nI actually really hate these kinds of variables. I think they likely\nmask various bugs (where the value might not be up to date where we\nthink it is) and anti-bugs (where we actually rely on the value being\nout of date but we don't know that we do because the code is so\nopaque). My vintage 2021 adventures in getting rid of the global\nvariable ThisTimeLineID and a few other global variables found some\nactual but minor bugs, also found a bunch of confused code that didn't\nreally do what it thought it did, and took up a huge amount of my time\ntrying to analyze what was happening. I'm not prepared to recommend\nwhat we should do in this particular case. I would like to believe\nthat the local copies can be eliminated somehow, but I haven't studied\nthe code or done benchmarking so I don't really know enough to guess\nwhat sort of code changes would or would not be good enough.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 23 Feb 2024 10:10:43 +0530", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Thanks for looking into this.\n\nOn Thu, Feb 22, 2024 at 1:54 AM Jeff Davis <pgsql@j-davis.com> wrote:\n>\n> > 3.\n> > @@ -6371,7 +6373,9 @@ GetFlushRecPtr(TimeLineID *insertTLI)\n> > If at all, a read\n> > barrier is warranted here, we can use atomic read with full barrier\n>\n> I don't think we need a full barrier but I'm fine with using\n> pg_atomic_read_membarrier_u64() if it's better for whatever reason.\n\nFor the sake of clarity and correctness, I've used\npg_atomic_read_membarrier_u64 everywhere for reading\nXLogCtl->LogwrtResult.Write and XLogCtl->LogwrtResult.Flush.\n\n> > 5. I guess we'd better use pg_atomic_read_u64_impl and\n> > pg_atomic_compare_exchange_u64_impl in\n> > pg_atomic_monotonic_advance_u64\n> > to reduce one level of function indirections.\n>\n> Aren't they inlined?\n\nYes, all of them are inlined. But, it seems like XXX_impl functions\nare being used in implementing exposed functions as a convention.\nTherefore, having pg_atomic_read_u64_impl and\npg_atomic_compare_exchange_u64_impl doesn't sound bad IMV.\n\n> > 6.\n> > + * Full barrier semantics (even when value is unchanged).\n> >\n> > + currval = pg_atomic_read_u64(ptr);\n> > + if (currval >= target_)\n> > + {\n> > + pg_memory_barrier();\n>\n> I don't think they are exactly equivalent: in the current patch, the\n> first pg_atomic_read_u64() could be reordered with earlier reads;\n> whereas that wouldn't work if using pg_atomic_read_membarrier_u64() it\n> could not be. I'm not sure whether that could create a performance\n> problem or not.\n\nI left it as-is.\n\n> > 9.\n> > + copyptr = pg_atomic_read_u64(&XLogCtl->LogwrtResult.Copy);\n> > + if (startptr + count > copyptr)\n> > + ereport(WARNING,\n> > + (errmsg(\"request to read past end of generated WAL;\n> > request %X/%X, current position %X/%X\",\n> > + LSN_FORMAT_ARGS(startptr + count),\n> > LSN_FORMAT_ARGS(copyptr))));\n> >\n> > Any specific reason for this to be a WARNING rather than an ERROR?\n>\n> Good question. WaitXLogInsertionsToFinish() uses a LOG level message\n> for the same situation. They should probably be the same log level, and\n> I would think it would be either PANIC or WARNING. I have no idea why\n> LOG was chosen.\n\nWaitXLogInsertionsToFinish adjusts upto after LOG so that the wait is\nnever past the current insert position even if a caller asks for\nreading WAL that doesn't yet exist. And the comment there says \"Here\nwe just assume that to mean that all WAL that has been reserved needs\nto be finished.\"\n\nIn contrast, WALReadFromBuffers kind of enforces callers to do\nWaitXLogInsertionsToFinish (IOW asks callers to send in the WAL that\nexists in the server). Therefore, an ERROR seems a reasonable choice\nto me, if PANIC sounds rather strong affecting all the postgres\nprocesses.\n\nFWIW, a PANIC when requested to flush past the end of WAL in\nWaitXLogInsertionsToFinish instead of LOG seems to be good. CF bot\nanimals don't complain -\nhttps://github.com/BRupireddy2/postgres/tree/be_harsh_when_request_to_flush_past_end_of_WAL_WIP.\n\n> 0001:\n>\n> * The comments on the two versions of the functions are redundant, and\n> the style in that header seems to be to omit the comment from the u64\n> version.\n\nRemoved comments atop 64-bit version.\n\n> * I'm not sure the AssertPointerAlignment is needed in the u32 version?\n\nBorrowed them from pg_atomic_read_u32 and\npg_atomic_compare_exchange_u32, just like how they assert before\ncalling XXX_impl versions. I don't see any problem with them.\n\n> 0002:\n>\n> * All updates to the non-shared LogwrtResult should update both values.\n> It's confusing to update those local values independently, because it\n> violates the invariant that LogwrtResult.Flush <= LogwrtResult.Write.\n>\n> > 2. I guess we need to update both the Write and Flush local copies in\n> > AdvanceXLInsertBuffer.\n>\n> I agree. Whenever we update the non-shared LogwrtResult, let's update\n> the whole thing. Otherwise it's confusing.\n\nYes, it's done that way now with a macro XLogUpdateLocalLogWrtResult\nusing pg_atomic_read_membarrier_u64 to read both Write and Flush ptrs.\n\n> * pg_memory_barrier() is not needed right before a spinlock\n\nGot rid of it as we read both Flush and Write local copies with\npg_atomic_read_membarrier_u64.\n\n> * As mentioned above, I think GetFlushRecPtr() needs two read barriers.\n> Also, I think the same for GetXLogWriteRecPtr().\n\nYes, it's done that way now with a macro XLogUpdateLocalLogWrtResult\nusing pg_atomic_read_membarrier_u64 to read both Write and Flush ptrs.\n\n> * In general, for any place using both Write and Flush, I think Flush\n> should be loaded first, followed by a read barrier, followed by a load\n> of the Write pointer.\n\nWhy read Flush first rather than Write? I think it's enough to do\n{read Write, read barrier, read Flush}. This works because Write is\nmonotonically advanced first before Flush using full barriers and we\ndon't get reordering issues between the readers and writers no? Am I\nmissing anything here?\n\n> And I think in most of those places there should\n> be a read barrier before the load of Flush, too, to avoid a stale value\n> in places that might matter.\n\nYes, using pg_atomic_read_membarrier_u64 for both Write and Flush makes it easy.\n\n> 0003:\n>\n> * We need to maintain the invariant that Copy >= Write >= Flush. I\n> believe that's always satisfied, because the\n> XLogWaitInsertionsToFinish() is always called before XLogWrite(). But\n> we should add an assert or runtime check of this invariant somewhere.\n\nYes, that invariant is already maintained by the server. Although, I'm\nnot fully agree, I added an assertion to WaitXLogInsertionsToFinish\nafter updating XLogCtl->LogwrtResult.Copy. CF bot is happy with it -\nhttps://github.com/BRupireddy2/postgres/tree/atomic_LogwrtResult_v13.\n\nPlease see the attached v13 patch set for further review.\n\n--\nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com", "msg_date": "Mon, 4 Mar 2024 21:15:00 +0530", "msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Mon, Mar 4, 2024 at 9:15 PM Bharath Rupireddy\n<bharath.rupireddyforpostgres@gmail.com> wrote:\n>\n> > 0003:\n> >\n> > * We need to maintain the invariant that Copy >= Write >= Flush. I\n> > believe that's always satisfied, because the\n> > XLogWaitInsertionsToFinish() is always called before XLogWrite(). But\n> > we should add an assert or runtime check of this invariant somewhere.\n>\n> Yes, that invariant is already maintained by the server. Although, I'm\n> not fully agree, I added an assertion to WaitXLogInsertionsToFinish\n> after updating XLogCtl->LogwrtResult.Copy. CF bot is happy with it -\n> https://github.com/BRupireddy2/postgres/tree/atomic_LogwrtResult_v13.\n\nI've now separated these invariants out into the 0004 patch.\n\nWith the assertions placed in WaitXLogInsertionsToFinish after\nupdating Copy ptr, I observed the assertion failing in one of the CF\nbot machines - https://cirrus-ci.com/build/6202112288227328. I could\nreproduce it locally with [1]. I guess the reason is that the Write\nand Flush ptrs are now updated independently and atomically without\nlock, they might drift and become out-of-order for a while if\nconcurrently they are accessed in WaitXLogInsertionsToFinish. So, I\nguess the right place to verify the invariant Copy >= Write >= Flush\nis in XLogWrite once Write and Flush ptrs in shared memory are updated\n(note that only one process at a time can do this). Accordingly, I've\nmoved the assertions to XLogWrite in the attached v14-0004 patch.\n\n> Please see the attached v13 patch set for further review.\n\nEarlier versions of the patches removed a piece of code ensuring\nshared WAL 'request' values did not fall beading the 'result' values.\nThere's a good reason for us to have it. So, I restored it.\n\n- /*\n- * Update shared-memory status\n- *\n- * We make sure that the shared 'request' values do not fall behind the\n- * 'result' values. This is not absolutely essential, but it saves some\n- * code in a couple of places.\n- */\n\nPlease see the attached v14 patch set.\n\n[1] for i in {1..100}; do make check\nPROVE_TESTS=\"t/027_stream_regress.pl\"; if [ $? -ne 0 ]; then echo \"The\ncommand failed on iteration $i\"; break; fi; done\n\n--\nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com", "msg_date": "Thu, 14 Mar 2024 13:08:23 +0530", "msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Thanks for keeping this moving forward. I gave your proposed patches a\nlook. One thing I didn't like much is that we're adding a new member\n(Copy) to XLogwrtAtomic -- but this struct is supposed to be a mirror of\nXLogwrtResult for use with atomic access. Since this new member is not\nadded to XLogwrtResult (because it's not needed there), the whole idea\nof there being symmetry between those two structs crumbles down.\nBecause we later stop using struct-assign anyway, meaning we no longer\nneed the structs to match, we can instead spell out the members in\nXLogCtl and call it a day.\n\nSo what I do in the attached 0001 is stop using the XLogwrtResult struct\nin XLogCtl and replace it with separate Write and Flush values, and add\nthe macro XLogUpdateLocalLogwrtResult() that copies the values of Write\nand Flush from the shared XLogCtl to the local variable given as macro\nargument. (I also added our idiomatic do {} while(0) to the macro\ndefinition, for safety). The new members are XLogCtl->logWriteResult\nand XLogCtl->logFlushResult and as of 0001 are just XLogRecPtr, so\nessentially identical semantics as the previous code. No atomic access\nyet!\n\n0002 then adds pg_atomic_monotonic_advance_u64. (I don't add the _u32\nvariant, because I don't think it's a great idea to add dead code. If\nlater we see a need for it we can put it in.) It also changes the two\nnew members to be atomics, changes the macro to use atomic read, and\nXLogWrite now uses monotonic increment. A couple of other places can\nmove the macro calls to occur outside the spinlock. Also, XLogWrite\ngains the invariant checking that involves Write and Flush.\n\nFinally, 0003 adds the Copy pointer to XLogCtl alongside Write and\nFlush, and updates WALReadFromBuffers to test that instead of the Write\npointer, and adds in XLogWrite the invariant checks that involve the\nCopy pointer.\n\nI haven't rerun Bharath test loop yet; will do so shortly.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"You're _really_ hosed if the person doing the hiring doesn't understand\nrelational systems: you end up with a whole raft of programmers, none of\nwhom has had a Date with the clue stick.\" (Andrew Sullivan)\nhttps://postgr.es/m/20050809113420.GD2768@phlogiston.dyndns.org", "msg_date": "Wed, 3 Apr 2024 13:19:40 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On 2024-Apr-03, Alvaro Herrera wrote:\n\n> So what I do in the attached 0001 is stop using the XLogwrtResult struct\n> in XLogCtl and replace it with separate Write and Flush values, and add\n> the macro XLogUpdateLocalLogwrtResult() that copies the values of Write\n> and Flush from the shared XLogCtl to the local variable given as macro\n> argument. (I also added our idiomatic do {} while(0) to the macro\n> definition, for safety). The new members are XLogCtl->logWriteResult\n> and XLogCtl->logFlushResult and as of 0001 are just XLogRecPtr, so\n> essentially identical semantics as the previous code. No atomic access\n> yet!\n\nBTW I forgot. I didn't like the name XLogUpdateLocalLogwrtResult() name\nmuch. What do you think about RefreshXLogWriteResult() instead?\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/\n\"How strange it is to find the words \"Perl\" and \"saner\" in such close\nproximity, with no apparent sense of irony. I doubt that Larry himself\ncould have managed it.\" (ncm, http://lwn.net/Articles/174769/)\n\n\n", "msg_date": "Wed, 3 Apr 2024 14:00:09 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Wed, Apr 3, 2024 at 4:49 PM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n>\n> Thanks for keeping this moving forward. I gave your proposed patches a\n> look. One thing I didn't like much is that we're adding a new member\n> (Copy) to XLogwrtAtomic -- but this struct is supposed to be a mirror of\n> XLogwrtResult for use with atomic access. Since this new member is not\n> added to XLogwrtResult (because it's not needed there), the whole idea\n> of there being symmetry between those two structs crumbles down.\n> Because we later stop using struct-assign anyway, meaning we no longer\n> need the structs to match, we can instead spell out the members in\n> XLogCtl and call it a day.\n\nHm, I have no objection to having separate variables in XLogCtl.\n\n> So what I do in the attached 0001 is stop using the XLogwrtResult struct\n> in XLogCtl and replace it with separate Write and Flush values, and add\n> the macro XLogUpdateLocalLogwrtResult() that copies the values of Write\n> and Flush from the shared XLogCtl to the local variable given as macro\n> argument. (I also added our idiomatic do {} while(0) to the macro\n> definition, for safety). The new members are XLogCtl->logWriteResult\n> and XLogCtl->logFlushResult and as of 0001 are just XLogRecPtr, so\n> essentially identical semantics as the previous code. No atomic access\n> yet!\n\n+1.\n\n> 0002 then adds pg_atomic_monotonic_advance_u64. (I don't add the _u32\n> variant, because I don't think it's a great idea to add dead code. If\n> later we see a need for it we can put it in.) It also changes the two\n> new members to be atomics, changes the macro to use atomic read, and\n> XLogWrite now uses monotonic increment. A couple of other places can\n> move the macro calls to occur outside the spinlock. Also, XLogWrite\n> gains the invariant checking that involves Write and Flush.\n\nI'm fine with not having the 32 bit variant of\npg_atomic_monotonic_advance. However, a recent commit bd5132db5 added\nboth 32 and 64 bit versions of pg_atomic_read_membarrier even though\n32 bit isn't being used.\n\n> Finally, 0003 adds the Copy pointer to XLogCtl alongside Write and\n> Flush, and updates WALReadFromBuffers to test that instead of the Write\n> pointer, and adds in XLogWrite the invariant checks that involve the\n> Copy pointer.\n\n+1.\n\nThe attached patches look good to me.\n\nAlso, I'm fine with renaming XLogUpdateLocalLogwrtResult() to\nRefreshXLogWriteResult().\n\n> I haven't rerun Bharath test loop yet; will do so shortly.\n\nI ran it a 100 times [1] on top of all the 3 patches, it looks fine.\n\n[1] for i in {1..100}; do make check\nPROVE_TESTS=\"t/027_stream_regress.pl\"; if [ $? -ne 0 ]; then echo \"The\ncommand failed on iteration $i\"; break; fi; done\n\n./configure --prefix=$PWD/pg17/ --enable-debug --enable-tap-tests\n--enable-cassert CC=/usr/bin/clang-14 > install.log && make -j 8\ninstall > install.log 2>&1 &\n\n--\nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com\n\n\n", "msg_date": "Wed, 3 Apr 2024 22:30:00 +0530", "msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On 2024-Apr-03, Bharath Rupireddy wrote:\n\n> On Wed, Apr 3, 2024 at 4:49 PM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n\n> > So what I do in the attached 0001 is stop using the XLogwrtResult struct\n> > in XLogCtl and replace it with separate Write and Flush values, and add\n> > the macro XLogUpdateLocalLogwrtResult() that copies the values of Write\n> > and Flush from the shared XLogCtl to the local variable given as macro\n> > argument. (I also added our idiomatic do {} while(0) to the macro\n> > definition, for safety). The new members are XLogCtl->logWriteResult\n> > and XLogCtl->logFlushResult and as of 0001 are just XLogRecPtr, so\n> > essentially identical semantics as the previous code. No atomic access\n> > yet!\n> \n> +1.\n\n> Also, I'm fine with renaming XLogUpdateLocalLogwrtResult() to\n> RefreshXLogWriteResult().\n\nOkay, I have pushed 0001 with the name change, will see about getting\nthe others in tomorrow.\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/\n\n\n", "msg_date": "Wed, 3 Apr 2024 19:57:32 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Wed, 2024-04-03 at 13:19 +0200, Alvaro Herrera wrote:\n> So what I do in the attached 0001 is stop using the XLogwrtResult\n> struct\n> in XLogCtl and replace it with separate Write and Flush values, and\n> add\n> the macro XLogUpdateLocalLogwrtResult() that copies the values of\n> Write\n> and Flush from the shared XLogCtl to the local variable given as\n> macro\n> argument.\n\n+1\n\n> 0002 then adds pg_atomic_monotonic_advance_u64.  (I don't add the\n> _u32\n> variant, because I don't think it's a great idea to add dead code. \n> If\n> later we see a need for it we can put it in.)  It also changes the\n> two\n> new members to be atomics, changes the macro to use atomic read, and\n> XLogWrite now uses monotonic increment.  A couple of other places can\n> move the macro calls to occur outside the spinlock.  Also, XLogWrite\n> gains the invariant checking that involves Write and Flush.\n\nTo maintain the invariant that Write >= Flush, I believe you need to\nalways store to Write first, then Flush; and load from Flush first,\nthen from Write. So RefreshXLogWriteResult should load Flush then load\nWrite, and the same for the Assert code. And in 0003, loading from Copy\nshould happen last.\n\nAlso, should pg_atomic_monotonic_advance_u64() return currval? I don't\nthink it's important for the current patches, but I could imagine a\ncaller wanting the most up-to-date value possible, even if it's beyond\nwhat the caller requested. Returning void seems slightly wasteful.\n\nOther than that, it looks good to me.\n\n> Finally, 0003 adds the Copy pointer to XLogCtl alongside Write and\n> Flush, and updates WALReadFromBuffers to test that instead of the\n> Write\n> pointer, and adds in XLogWrite the invariant checks that involve the\n> Copy pointer.\n\nLooks good to me.\n\nRegards,\n\tJeff Davis\n\n\n\n", "msg_date": "Wed, 03 Apr 2024 13:15:28 -0700", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "I've noticed a few things here, v16 attached with some rather largish\nchanges.\n\n1. Using pg_atomic_write_membarrier_u64 is useless and it imposes mora\nbarriers than we actually need. So I switched back to\npg_atomic_write_u64 and add one barrier between the two writes. Same\nfor reads.\n\n2. Using monotonic_advance for Write and Flush is useless. We can use a\nsimple atomic_write with a write barrier in between. The reason is\nthat, as Andres said[1], we only write those with WALWriteLock held, so\nit's not possible for them to move forward while we aren't looking. All\ncallers of XLogWrite do RefreshXLogWriteResult() with the WALWriteLock\nheld. Therefore we can just use pg_atomic_write_u64. Consequently I\nmoved the addition of the monotonic advance function to the patch that\nadds Copy.\n\n3. Testing the invariant that the Copy pointer cannot be 0 is useless,\nbecause we initialize that pointer to EndOfLog during StartupXLOG.\nSo, removed.\n\n4. If we're not modifying any callers of WALReadFromBuffers(), then\nAFAICS the added check that the request is not past the Copy pointer is\nuseless. In a quick look at that code, I think we only try to read data\nthat's been flushed, not written, so the stricter check that we don't\nread data that hasn't been Copied does nothing. (Honestly I'm not sure\nthat we want XLogSendPhysical to be reading data that has not been\nwritten, or do we?) Please argue why we need this patch.\n\n5. The existing weird useless-looking block at the end of XLogWrite is\nthere because we used to have it to declare a volatile pointer to\nXLogCtl (cf. commit 6ba4ecbf477e). That's no longer needed, so we\ncould remove it. Or we could leave it alone (just because it's ancient\nand it doesn't hurt anything), but there's no reason to have the new\ninvariant-testing block inside the same block. So I added another weird\nuseless-looking block, except that this one does have two variable\ndeclaration at its top.\n\n6. In a few places, we read both Write and Flush to only use one of\nthem. This is wasteful and we could dial this back to reading only the\none we need. Andres suggested as much in [1]. I didn't touch this in\nthe current patch, and I don't necessarily think we need to address it\nright now. Addressing this should probably done similar to what I\nposted in [2]'s 0002.\n\n[1] https://postgr.es/m/20210130023011.n545o54j65t4kgxn@alap3.anarazel.de\n[2] https://postgr.es/m/202203221611.hqbjdinzsbu2@alvherre.pgsql\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/", "msg_date": "Thu, 4 Apr 2024 19:45:04 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Thu, 2024-04-04 at 19:45 +0200, Alvaro Herrera wrote:\n> 1. Using pg_atomic_write_membarrier_u64 is useless and it imposes\n> mora\n> barriers than we actually need.  So I switched back to\n> pg_atomic_write_u64 and add one barrier between the two writes.  Same\n> for reads.\n\n+1.\n\nThis looks correct to me. Just before the writes there's a spinlock,\nwhich acts as a full barrier; and just afterwards, the function returns\nand the WALWriteLock is released, again acting as a full barrier. The\nwrite barrier in between enforces the Write >= Flush invariant.\n\n> 2. Using monotonic_advance for Write and Flush is useless.\n\n+1.\n\n> 3. Testing the invariant that the Copy pointer cannot be 0 is\n> useless,\n> because we initialize that pointer to EndOfLog during StartupXLOG.\n> So, removed.\n\n+1.\n\n> 4. If we're not modifying any callers of WALReadFromBuffers(), then\n> AFAICS the added check that the request is not past the Copy pointer\n> is\n> useless.  In a quick look at that code, I think we only try to read\n> data\n> that's been flushed, not written, so the stricter check that we don't\n> read data that hasn't been Copied does nothing.\n\nBharath has indicated that he may call WALReadFromBuffers() in an\nextension, so I believe some error checking is appropriate there.\n\n>   (Honestly I'm not sure\n> that we want XLogSendPhysical to be reading data that has not been\n> written, or do we?)\n\nNot yet, but there has been some discussion[1][2] about future work to\nallow replicating data before it's been flushed locally.\n\n>   Please argue why we need this patch.\n\nI'm not sure what you mean by \"this patch\"?\n\n> 5. The existing weird useless-looking block at the end of XLogWrite\n> is\n> there because we used to have it to declare a volatile pointer to\n> XLogCtl (cf.  commit 6ba4ecbf477e).  That's no longer needed, so we\n> could remove it.  Or we could leave it alone (just because it's\n> ancient\n> and it doesn't hurt anything), but there's no reason to have the new\n> invariant-testing block inside the same block.  So I added another\n> weird\n> useless-looking block, except that this one does have two variable\n> declaration at its top.\n\nThat didn't bother me, but it could be cleaned up a bit in a later\npatch.\n\n> 6. In a few places, we read both Write and Flush to only use one of\n> them.  This is wasteful and we could dial this back to reading only\n> the\n> one we need.  Andres suggested as much in [1].  I didn't touch this\n> in\n> the current patch, and I don't necessarily think we need to address\n> it\n> right now.  Addressing this should probably done similar to what I\n> posted in [2]'s 0002.\n\nI agree that it should be a separate patch. I haven't thought about the\nconsequences of making them fully independent -- I think that means we\ngive up the invariant that Copy >= Write >= Flush?\n\n\nRegarding the patches themselves, 0001 looks good to me.\n\nFor 0002, did you consider having pg_atomic_monotonic_advance_u64()\nreturn the currval?\n\t\nRegards,\n\tJeff Davis\n\n[1]\nhttps://www.postgresql.org/message-id/CALj2ACV6rS%2B7iZx5%2BoAvyXJaN4AG-djAQeM1mrM%3DYSDkVrUs7g%40mail.gmail.com\n[2]\nhttps://www.postgresql.org/message-id/20230125211540.zylu74dj2uuh3k7w%40awork3.anarazel.de\n[3]\nhttps://www.postgresql.org/message-id/CALj2ACW65mqn6Ukv57SqDTMzAJgd1N_AdQtDgy%2BgMDqu6v618Q%40mail.gmail.com\n\n\n\n", "msg_date": "Thu, 04 Apr 2024 15:50:58 -0700", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Fri, Apr 5, 2024 at 4:21 AM Jeff Davis <pgsql@j-davis.com> wrote:\n>\n> > 4. If we're not modifying any callers of WALReadFromBuffers(), then\n> > AFAICS the added check that the request is not past the Copy pointer\n> > is\n> > useless. In a quick look at that code, I think we only try to read\n> > data\n> > that's been flushed, not written, so the stricter check that we don't\n> > read data that hasn't been Copied does nothing.\n>\n> Bharath has indicated that he may call WALReadFromBuffers() in an\n> extension, so I believe some error checking is appropriate there.\n>\n> > (Honestly I'm not sure\n> > that we want XLogSendPhysical to be reading data that has not been\n> > written, or do we?)\n>\n> Not yet, but there has been some discussion[1][2] about future work to\n> allow replicating data before it's been flushed locally.\n\nRight. Although callers of WALReadFromBuffers() in core postgres\ndoesn't need it now (in future, they will), but it allows one to write\nsomething up externally - for example, see 0004 patch in\nhttps://www.postgresql.org/message-id/CALj2ACWmW+1ZdYE0BD5-4KVLzYGn3=pudomwPHuHmi4YQuOFSg@mail.gmail.com\nwhere I implemented a xlogreader page_read callback that just keeps\nreading the WAL that's fully copied to WAL buffers.\n\n> Regarding the patches themselves, 0001 looks good to me.\n\nA few comments on 0001:\n\n1.\n /*\n * Update local copy of shared XLogCtl->log{Write,Flush}Result\n+ *\n+ * It's critical that Flush always trails Write, so the order of the reads is\n+ * important, as is the barrier.\n */\n #define RefreshXLogWriteResult(_target) \\\n do { \\\n- _target.Write = XLogCtl->logWriteResult; \\\n- _target.Flush = XLogCtl->logFlushResult; \\\n+ _target.Flush = pg_atomic_read_u64(&XLogCtl->logFlushResult); \\\n+ pg_read_barrier(); \\\n+ _target.Write = pg_atomic_read_u64(&XLogCtl->logWriteResult); \\\n } while (0)\n\nIs it \"Flush always trails Write\" or \"Flush always leades Write\"? I\nguess the latter, no?\n\n2.\n+\n+ pg_atomic_write_u64(&XLogCtl->logWriteResult, LogwrtResult.Write);\n+ pg_write_barrier();\n+ pg_atomic_write_u64(&XLogCtl->logFlushResult, LogwrtResult.Flush);\n }\n\nMaybe add the reason as to why we had to write logWriteResult first\nand then logFlushResult, similar to the comment atop\nRefreshXLogWriteResult?\n\n> For 0002, did you consider having pg_atomic_monotonic_advance_u64()\n> return the currval?\n\n+1 for returning currval here.\n\nExcept for the above comments, the patches look good to me. I've also\nrun the test loop for any assertion failure - for i in {1..100}; do\nmake check PROVE_TESTS=\"t/027_stream_regress.pl\"; if [ $? -ne 0 ];\nthen echo \"The command failed on iteration $i\"; break; fi; done.\n\n--\nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com\n\n\n", "msg_date": "Fri, 5 Apr 2024 09:59:09 +0530", "msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On 2024-Apr-05, Bharath Rupireddy wrote:\n\n> 1.\n> /*\n> * Update local copy of shared XLogCtl->log{Write,Flush}Result\n> + *\n> + * It's critical that Flush always trails Write, so the order of the reads is\n> + * important, as is the barrier.\n> */\n> #define RefreshXLogWriteResult(_target) \\\n> do { \\\n> - _target.Write = XLogCtl->logWriteResult; \\\n> - _target.Flush = XLogCtl->logFlushResult; \\\n> + _target.Flush = pg_atomic_read_u64(&XLogCtl->logFlushResult); \\\n> + pg_read_barrier(); \\\n> + _target.Write = pg_atomic_read_u64(&XLogCtl->logWriteResult); \\\n> } while (0)\n> \n> Is it \"Flush always trails Write\" or \"Flush always leades Write\"? I\n> guess the latter, no?\n\nWell, Flush cannot lead Write. We cannot Flush what hasn't been\nWritten! To me, \"Flush trails Write\" means that flush is behind. That\nseems supported by Merriam-Webster[1], which says in defining it as a\ntransitive verb\n\n3 a : to follow upon the scent or trace of : TRACK\n b : to follow in the footsteps of : PURSUE\n c : to follow along behind\n d : to lag behind (someone, such as a competitor)\n\nMaybe it's not super clear as a term. We could turn it around and say \"Write\nalways leads Flush\".\n\n[1] https://www.merriam-webster.com/dictionary/trail\n\nThe reason we have the barrier, and the reason we write and read them in\nthis order, is that we must never read a Flush value that is newer than\nthe Write value we read. That is: the values are written in pairs\n(w1,f1) first, (w2,f2) next, and so on. It's okay if we obtain (w2,f1)\n(new write, old flush), but it's not okay if we obtain (w1,f2) (old\nwrite, new flush). If we did, we might end up with a Flush value that's\nahead of Write, violating the invariant. \n\n> 2.\n> +\n> + pg_atomic_write_u64(&XLogCtl->logWriteResult, LogwrtResult.Write);\n> + pg_write_barrier();\n> + pg_atomic_write_u64(&XLogCtl->logFlushResult, LogwrtResult.Flush);\n> }\n> \n> Maybe add the reason as to why we had to write logWriteResult first\n> and then logFlushResult, similar to the comment atop\n> RefreshXLogWriteResult?\n\nHmm, I had one there and removed it. I'll put something back.\n\n> > For 0002, did you consider having pg_atomic_monotonic_advance_u64()\n> > return the currval?\n> \n> +1 for returning currval here.\n\nOh yeah, I had that when the monotonic stuff was used by 0001 but lost\nit when I moved to 0002. I'll push 0001 now and send an updated 0002\nwith the return value added.\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/\n\"La rebeldía es la virtud original del hombre\" (Arthur Schopenhauer)\n\n\n", "msg_date": "Fri, 5 Apr 2024 10:41:01 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Couldn't push: I tested with --disable-atomics --disable-spinlocks and\nthe tests fail because the semaphore for the atomic variables is not\nalways initialized. This is weird -- it's like a client process is\nrunning at a time when StartupXLOG has not initialized the variable ...\nso the initialization in the other place was not completely wrong.\nI'll investigate after lunch. Here's v16.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"XML!\" Exclaimed C++. \"What are you doing here? You're not a programming\nlanguage.\"\n\"Tell that to the people who use me,\" said XML.\nhttps://burningbird.net/the-parable-of-the-languages/", "msg_date": "Fri, 5 Apr 2024 13:54:45 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Pushed 0001. Here's the patch that adds the Copy position one more\ntime, with the monotonic_advance function returning the value.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/", "msg_date": "Fri, 5 Apr 2024 19:55:32 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Fri, 2024-04-05 at 13:54 +0200, Alvaro Herrera wrote:\n> Couldn't push: I tested with --disable-atomics --disable-spinlocks\n> and\n> the tests fail because the semaphore for the atomic variables is not\n> always initialized.  This is weird -- it's like a client process is\n> running at a time when StartupXLOG has not initialized the variable\n> ...\n> so the initialization in the other place was not completely wrong.\n\nIt looks like you solved the problem and pushed the first patch. Looks\ngood to me.\n\nPatch 0002 also looks good to me, after a mostly-trivial rebase (just\nremember to initialize logCopyResult).\n\nMinor comments:\n\n* You could consider using a read barrier before reading the Copy ptr,\nor using the pg_atomic_read_membarrier_u64() variant. I don't see a\ncorrectness problem, but it might be slightly more clear and I don't\nsee a lot of downside.\n\n* Also, I assume that the Max() call in\npg_atomic_monotonic_advance_u64() is just for clarity? Surely the\ncurrval cannot be less than _target when it returns. I'd probably just\ndo Assert(currval >= _target) and then return currval.\n\nRegards,\n\tJeff Davis\n\n\n\n", "msg_date": "Fri, 05 Apr 2024 11:22:40 -0700", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Sat, Apr 6, 2024 at 6:55 AM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> Pushed 0001.\n\nCould that be related to the 3 failures on parula that look like this?\n\nTRAP: failed Assert(\"node->next == 0 && node->prev == 0\"), File:\n\"../../../../src/include/storage/proclist.h\", Line: 63, PID: 29119\n2024-04-05 16:16:26.812 UTC [29114:15] pg_regress/drop_operator LOG:\nstatement: DROP OPERATOR <|(bigint, bigint);\npostgres: postgres regression [local] CREATE\nROLE(ExceptionalCondition+0x4c)[0x9b3fdc]\npostgres: postgres regression [local] CREATE ROLE[0x8529e4]\npostgres: postgres regression [local] CREATE\nROLE(LWLockWaitForVar+0xec)[0x8538fc]\npostgres: postgres regression [local] CREATE ROLE[0x54c7d4]\npostgres: postgres regression [local] CREATE ROLE(XLogFlush+0xf0)[0x552600]\npostgres: postgres regression [local] CREATE ROLE[0x54a9b0]\npostgres: postgres regression [local] CREATE ROLE[0x54bbdc]\n\nHmm, the comments for LWLockWaitForVar say:\n\n * Be aware that LWLockConflictsWithVar() does not include a memory barrier,\n * hence the caller of this function may want to rely on an explicit barrier or\n * an implied barrier via spinlock or LWLock to avoid memory ordering issues.\n\nBut that seems to be more likely to make LWLockWaitForVar suffer data\nraces (ie hang), not break assertions about LWLock sanity, so I don't\nknow what's going on there. I happened to have a shell on a Graviton\nbox, but I couldn't reproduce it after a while...\n\n\n", "msg_date": "Sat, 6 Apr 2024 16:50:24 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Sat, Apr 6, 2024 at 9:21 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n>\n> On Sat, Apr 6, 2024 at 6:55 AM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> > Pushed 0001.\n>\n> Could that be related to the 3 failures on parula that look like this?\n>\n> TRAP: failed Assert(\"node->next == 0 && node->prev == 0\"), File:\n> \"../../../../src/include/storage/proclist.h\", Line: 63, PID: 29119\n> 2024-04-05 16:16:26.812 UTC [29114:15] pg_regress/drop_operator LOG:\n> statement: DROP OPERATOR <|(bigint, bigint);\n> postgres: postgres regression [local] CREATE\n> ROLE(ExceptionalCondition+0x4c)[0x9b3fdc]\n> postgres: postgres regression [local] CREATE ROLE[0x8529e4]\n> postgres: postgres regression [local] CREATE\n> ROLE(LWLockWaitForVar+0xec)[0x8538fc]\n> postgres: postgres regression [local] CREATE ROLE[0x54c7d4]\n> postgres: postgres regression [local] CREATE ROLE(XLogFlush+0xf0)[0x552600]\n> postgres: postgres regression [local] CREATE ROLE[0x54a9b0]\n> postgres: postgres regression [local] CREATE ROLE[0x54bbdc]\n>\n> Hmm, the comments for LWLockWaitForVar say:\n>\n> * Be aware that LWLockConflictsWithVar() does not include a memory barrier,\n> * hence the caller of this function may want to rely on an explicit barrier or\n> * an implied barrier via spinlock or LWLock to avoid memory ordering issues.\n>\n> But that seems to be more likely to make LWLockWaitForVar suffer data\n> races (ie hang), not break assertions about LWLock sanity, so I don't\n> know what's going on there. I happened to have a shell on a Graviton\n> box, but I couldn't reproduce it after a while...\n\nThanks for reporting. I'll try to spin up a similar instance like\nparula and reproduce. Meanwhile, I'm wondering if it is somehow\nrelated to what's discussed in \"Why is parula failing?\"\nhttps://www.postgresql.org/message-id/4009739.1710878318%40sss.pgh.pa.us.\nIt seems like parula is behaving unexpectedly because of the compiler\nand other stuff.\n\n-- \nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com\n\n\n", "msg_date": "Sat, 6 Apr 2024 12:08:45 +0530", "msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On 2024-Apr-05, Jeff Davis wrote:\n\n> Minor comments:\n\n> * Also, I assume that the Max() call in\n> pg_atomic_monotonic_advance_u64() is just for clarity? Surely the\n> currval cannot be less than _target when it returns. I'd probably just\n> do Assert(currval >= _target) and then return currval.\n\nUhh ... my understanding of pg_atomic_compare_exchange_u64 is that\n*expected is set to the value that's stored in *ptr prior to the\nexchange. Its comment\n\n * Atomically compare the current value of ptr with *expected and store newval\n * iff ptr and *expected have the same value. The current value of *ptr will\n * always be stored in *expected.\n\nis actually not very clear, because what does \"current\" mean in this\ncontext? Is the original \"current\" value, or is it the \"current\" value\nafter the exchange? Anyway, looking at the spinlock-emulated code for\npg_atomic_compare_exchange_u32_impl in atomics.c,\n\n\t/* perform compare/exchange logic */\n\tret = ptr->value == *expected;\n\t*expected = ptr->value;\n\tif (ret)\n\t\tptr->value = newval;\n\nit's clear that *expected receives the original value, not the new one.\n\nBecause of this behavior, not doing the Max() would return the obsolete\nvalue rather than the one we just installed. (It would only work\ncorrectly without Max() when our cmpxchg operation \"fails\", that is,\nsomebody else incremented the value past the one we want to install.)\n\n\nAnother reason is that when I used pg_atomic_monotonic_advance_u64 with\nthe Write and Flush pointers and did not have the Max(), the assertion\nfailed pretty quickly :-)\n\n-- \nÁlvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/\nAl principio era UNIX, y UNIX habló y dijo: \"Hello world\\n\".\nNo dijo \"Hello New Jersey\\n\", ni \"Hello USA\\n\".\n\n\n", "msg_date": "Sat, 6 Apr 2024 18:13:19 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Sat, 2024-04-06 at 18:13 +0200, Alvaro Herrera wrote:\n> my understanding of pg_atomic_compare_exchange_u64 is that\n> *expected is set to the value that's stored in *ptr prior to the\n> exchange.\n\nSorry, my mistake. Your version looks good.\n\nRegards,\n\tJeff Davis\n\n\n\n", "msg_date": "Sat, 06 Apr 2024 10:46:05 -0700", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "I pushed the \"copy\" pointer now, except that I renamed it to \"insert\",\nwhich is what we call the operation being tracked. I also added some\ncomments.\n\nOne perhaps significant change from what Bharath submitted is that we\nnow use the return value from monotonic advance to return an updated\nvalue of finishedUpto from WaitXLogInsertionsToFinish. I think this is\na useful optimization: the only caller of WaitXLogInsertionsToFinish\nwhich cares about its return value is XLogFlush, which AFAICS benefits\nfrom having a more up-to-date value.\n\nAlso, I did adopt your (Jeff's) idea of using a barrier when reading\nlogInsertResult in WaitXLogInsertionsToFinish. If I understand\ncorrectly, this is actually useful: if some other CPU core was also\nrecently busy waiting for xlog insertions and wrote an updated version\nof logInsertResult that's past what we last saw, we benefit from an\nupdated value because we can skip the spinlock dance and WAL-insert-var\nstuff altogether. With no barrier, we would potentially see an outdated\nvalue of logInsertResult and waste a lot of effort to get it updated.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"Those who use electric razors are infidels destined to burn in hell while\nwe drink from rivers of beer, download free vids and mingle with naked\nwell shaved babes.\" (http://slashdot.org/comments.pl?sid=44793&cid=4647152)\n\n\n", "msg_date": "Sun, 7 Apr 2024 14:19:29 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Sun, 2024-04-07 at 14:19 +0200, Alvaro Herrera wrote:\n> I pushed the \"copy\" pointer now, except that I renamed it to\n> \"insert\",\n> which is what we call the operation being tracked.  I also added some\n> comments.\n\nThe \"copy\" pointer, as I called it, is not the same as the \"insert\"\npointer (as returned by GetXLogInsertRecPtr()).\n\nLSNs before the \"insert\" pointer are reserved for WAL inserters (and\nmay or may not have made it to WAL buffers yet). LSNs before the \"copy\"\npointer are written to WAL buffers with CopyXLogRecordToWAL() (and may\nor may not have been evicted to the OS file yet).\n\nOther than that, looks good, thank you.\n\nRegards,\n\tJeff Davis\n\n\n\n", "msg_date": "Sun, 07 Apr 2024 12:47:00 -0700", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On 2024-Apr-07, Jeff Davis wrote:\n\n> On Sun, 2024-04-07 at 14:19 +0200, Alvaro Herrera wrote:\n> > I pushed the \"copy\" pointer now, except that I renamed it to\n> > \"insert\",\n> > which is what we call the operation being tracked.  I also added some\n> > comments.\n> \n> The \"copy\" pointer, as I called it, is not the same as the \"insert\"\n> pointer (as returned by GetXLogInsertRecPtr()).\n> \n> LSNs before the \"insert\" pointer are reserved for WAL inserters (and\n> may or may not have made it to WAL buffers yet). LSNs before the \"copy\"\n> pointer are written to WAL buffers with CopyXLogRecordToWAL() (and may\n> or may not have been evicted to the OS file yet).\n\nIt seems a matter of interpretation. WAL insertion starts with\nreserving the space (in ReserveXLogInsertLocation) and moving the\nCurrBytePos point forward; the same WAL insertion completes when the\nactual data has been copied to the buffers. It is this process as a\nwhole that we can an insertion. CurrBytePos (what GetXLogInsertRecPtr\nreturns) is the point where the next insertions are going to occur; the\nnew logInsertResult is the point where previous insertions are known to\nhave completed.\n\nWe could think about insertions as something that's happening to a range\nof bytes. CurrBytePos is the high end of that range, logInsertResult is\nits low end. (Although in reality we don't know the true low end,\nbecause the process writing the oldest WAL doesn't advertise as soon as\nit finishes its insertion, because it doesn't know that it is writing\nthe oldest. We only know that X is this \"oldest known\" after we have\nwaited for all those that were inserting earlier than X to have\nfinished.)\n\nMy trouble with the \"copy\" term is that we don't use that term anywhere\nin relation to WAL. It's a term we don't need. This \"copy\" is in\nreality just the insertion, after it's finished. The \"Result\" suffix\nis intended to convey that it's the point where the operation has\nsuccessfully finished.\n\nMaybe we can add some commentary to make this clearer.\n\nNow, if you're set on renaming the variable back to Copy, I won't\nobject.\n\nLastly, I just noticed that I forgot credits and discussion link in that\ncommit message. I would have attributed authorship to Bharath though,\nbecause I had not realized that this patch had actually been written by\nyou initially[1]. My apologies.\n\n[1] https://postgr.es/m/727449f3151c6b9ab76ba706fa4d30bf7b03ad4f.camel@j-davis.com\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\n\n", "msg_date": "Mon, 8 Apr 2024 10:24:15 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On Mon, 2024-04-08 at 10:24 +0200, Alvaro Herrera wrote:\n> My trouble with the \"copy\" term is that we don't use that term\n> anywhere\n> in relation to WAL.\n\nI got the term from CopyXLogRecordToWAL().\n\n> This \"copy\" is in\n> reality just the insertion, after it's finished.  The \"Result\" suffix\n> is intended to convey that it's the point where the operation has\n> successfully finished.\n\nThat's a convincing point.\n\n> Maybe we can add some commentary to make this clearer.\n\nFor now, I'd just suggest a comment on GetXLogInsertRecPtr() explaining\nwhat it's returning and how that's different from logInsertResult.\n\nIn the future, it would be nice to clarify where variable names like\nreservedUpto and CurrBytePos fit in. Also the external documentation\nfor pg_current_wal_insert_lsn() is a bit ambiguous. \n\n> Lastly, I just noticed that I forgot credits and discussion link in\n> that\n> commit message.  I would have attributed authorship to Bharath\n> though,\n> because I had not realized that this patch had actually been written\n> by\n> you initially[1].  My apologies.\n\nNo worries. Thank you for reviewing and committing it.\n\nRegards,\n\tJeff Davis\n\n\n\n", "msg_date": "Mon, 08 Apr 2024 09:13:22 -0700", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Hello Alvaro and Bharath,\n\n07.04.2024 15:19, Alvaro Herrera wrote:\n> I pushed the \"copy\" pointer now, except that I renamed it to \"insert\",\n> which is what we call the operation being tracked. I also added some\n> comments.\n\nI've discovered that Windows x86 build fails tests after commit f3ff7bf83.\nUsing \"x86 Native Tools Command Prompt for VS 2022\", I do:\nmeson setup build -Dcassert=true\ncd build\nninja\nmeson test --suite setup\n\nand get:\n1/3 postgresql:setup / tmp_install               OK 1.56s\n2/3 postgresql:setup / install_test_files        OK 0.09s\n3/3 postgresql:setup / initdb_cache              FAIL 1.88s   exit status 1\n\ntestlog.txt contains:\nrunning bootstrap script ...\n----------------------------------- stderr -----------------------------------\nTRAP: failed Assert(\"TYPEALIGN(8, (uintptr_t)(&currval)) == (uintptr_t)(&currval)\"), File: \n\"...\\src\\include\\port/atomics.h\", Line: 597, PID: 7556\nchild process was terminated by exception 0xC0000409\n\nOn f3ff7bf83~1, `meson test --suite setup` passes for me.\n\n(I could not find if support for 32-bit Windows ended, so decided to\nreport this.)\n\nBest regards,\nAlexander\n\n\n", "msg_date": "Sat, 29 Jun 2024 10:00:00 +0300", "msg_from": "Alexander Lakhin <exclusion@gmail.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Hi\n\nOn 2024-Jun-29, Alexander Lakhin wrote:\n\n> ----------------------------------- stderr -----------------------------------\n> TRAP: failed Assert(\"TYPEALIGN(8, (uintptr_t)(&currval)) ==\n> (uintptr_t)(&currval)\"), File: \"...\\src\\include\\port/atomics.h\", Line: 597,\n> PID: 7556\n> child process was terminated by exception 0xC0000409\n\nOh. This is the new assertion in pg_atomic_monotonic_advance_u64() and\ntherefore the only possible culprit could be logInsertResult in\nXLogCtlData. Does it work if you do this?\n\ndiff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c\nindex 8dcdf5a764..e581488d57 100644\n--- a/src/backend/access/transam/xlog.c\n+++ b/src/backend/access/transam/xlog.c\n@@ -468,7 +468,7 @@ typedef struct XLogCtlData\n \tXLogRecPtr\tlastSegSwitchLSN;\n \n \t/* These are accessed using atomics -- info_lck not needed */\n-\tpg_atomic_uint64 logInsertResult;\t/* last byte + 1 inserted to buffers */\n+\tpg_atomic_uint64 logInsertResult pg_attribute_aligned(8);\t/* last byte + 1 inserted to buffers */\n \tpg_atomic_uint64 logWriteResult;\t/* last byte + 1 written out */\n \tpg_atomic_uint64 logFlushResult;\t/* last byte + 1 flushed */\n \n\nThanks\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"Use it up, wear it out, make it do, or do without\"\n\n\n", "msg_date": "Sat, 29 Jun 2024 12:23:02 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Hi Alvaro,\n\nThank you for looking at this!\n\n29.06.2024 13:23, Alvaro Herrera wrote:\n>> TRAP: failed Assert(\"TYPEALIGN(8, (uintptr_t)(&currval)) ==\n>> (uintptr_t)(&currval)\"), File: \"...\\src\\include\\port/atomics.h\", Line: 597,\n>> PID: 7556\n>> child process was terminated by exception 0xC0000409\n> Oh. This is the new assertion in pg_atomic_monotonic_advance_u64() and\n> therefore the only possible culprit could be logInsertResult in\n> XLogCtlData. Does it work if you do this?\n>\n> diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c\n> index 8dcdf5a764..e581488d57 100644\n> --- a/src/backend/access/transam/xlog.c\n> +++ b/src/backend/access/transam/xlog.c\n> @@ -468,7 +468,7 @@ typedef struct XLogCtlData\n> \tXLogRecPtr\tlastSegSwitchLSN;\n> \n> \t/* These are accessed using atomics -- info_lck not needed */\n> -\tpg_atomic_uint64 logInsertResult;\t/* last byte + 1 inserted to buffers */\n> +\tpg_atomic_uint64 logInsertResult pg_attribute_aligned(8);\t/* last byte + 1 inserted to buffers */\n> \tpg_atomic_uint64 logWriteResult;\t/* last byte + 1 written out */\n> \tpg_atomic_uint64 logFlushResult;\t/* last byte + 1 flushed */\n\nIt doesn't, but the following works for me:\n  static inline uint64\n  pg_atomic_monotonic_advance_u64(volatile pg_atomic_uint64 *ptr, uint64 target_)\n  {\n-       uint64          currval;\n+       pg_attribute_aligned(8) uint64          currval;\n\nbecause the failed assertion is:\n#ifndef PG_HAVE_ATOMIC_U64_SIMULATION\n     AssertPointerAlignment(&currval, 8);\n#endif\n\nBest regards,\nAlexander\n\n\n", "msg_date": "Sat, 29 Jun 2024 15:00:00 +0300", "msg_from": "Alexander Lakhin <exclusion@gmail.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Hello,\n\nOn 2024-Jun-29, Alexander Lakhin wrote:\n\n> It doesn't, but the following works for me:\n>  static inline uint64\n>  pg_atomic_monotonic_advance_u64(volatile pg_atomic_uint64 *ptr, uint64 target_)\n>  {\n> -       uint64          currval;\n> +       pg_attribute_aligned(8) uint64          currval;\n> \n> because the failed assertion is:\n> #ifndef PG_HAVE_ATOMIC_U64_SIMULATION\n>     AssertPointerAlignment(&currval, 8);\n> #endif\n\nHah, thank you.\n\nIn the meantime I noticed that pg_attribute_aligned() is not supported\nin every platform/compiler, so for safety sake I think it's better to go\nwith what we do for PGAlignedBlock: use a union with a double member.\nThat should be 8-byte aligned on x86 as well, unless I misunderstand.\n\nBTW if things works after this fix, I suggest you get a buildfarm member\nrunning with this configuration. Otherwise it's quite likely that we'll\nbreak it again. Or we could just decide we don't care about this\nparticular platform ... but AFAICS the buildfarm does have other 32-bit\nanimals running.\n\n[ looks at buildfarm ]\n\nOh! while looking at Adder's config, I noticed this line:\nChecking for alignment of \"double\" : 4 \nSo, I do misunderstand doubles.\n\nSo my patch is not going to work. There seems to be nothing that has\nalignment 8 there, so I guess we're back to using\npg_attribute_aligned() and abort the compile if that doesn't exist.\n\n-- \nÁlvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/\n\"La gente vulgar sólo piensa en pasar el tiempo;\nel que tiene talento, en aprovecharlo\"", "msg_date": "Mon, 1 Jul 2024 11:10:24 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Alvaro Herrera <alvherre@alvh.no-ip.org> writes:\n>> because the failed assertion is:\n>> #ifndef PG_HAVE_ATOMIC_U64_SIMULATION\n>>     AssertPointerAlignment(&currval, 8);\n>> #endif\n\nPerhaps this assertion is what is wrong? If the platform has no\nnative 8-byte alignment requirement, why do we think that atomics\nneed it?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 01 Jul 2024 10:08:23 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On 2024-Jul-01, Tom Lane wrote:\n\n> Alvaro Herrera <alvherre@alvh.no-ip.org> writes:\n> >> because the failed assertion is:\n> >> #ifndef PG_HAVE_ATOMIC_U64_SIMULATION\n> >>     AssertPointerAlignment(&currval, 8);\n> >> #endif\n> \n> Perhaps this assertion is what is wrong? If the platform has no\n> native 8-byte alignment requirement, why do we think that atomics\n> need it?\n\nOh, that's a good question. TBH I just copied the assertion from the\nother routines for 64-bit variables in the same file. But I think\nthat's correct. We're gating the assertion on _not_ having emulation,\nwhich must mean we have native atomics; on MSVC, if I read the #ifdef\nmaze correctly, that's implemented using _InterlockedCompareExchange,\nwhose docs state:\n\n: The variables for this function must be aligned on a 64-bit boundary;\n: otherwise, this function will behave unpredictably on multiprocessor x86\n: systems and any non-x86 systems. See _aligned_malloc.\nhttps://learn.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-interlockedcompareexchange64\n\nSo I think the assertion is correct.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"[PostgreSQL] is a great group; in my opinion it is THE best open source\ndevelopment communities in existence anywhere.\" (Lamar Owen)\n\n\n", "msg_date": "Mon, 1 Jul 2024 16:35:02 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Maybe we can do something like this,\n\ndiff --git a/src/include/port/atomics.h b/src/include/port/atomics.h\nindex 78987f3154..f6fa90bad8 100644\n--- a/src/include/port/atomics.h\n+++ b/src/include/port/atomics.h\n@@ -580,7 +580,20 @@ pg_atomic_sub_fetch_u64(volatile pg_atomic_uint64 *ptr, int64 sub_)\n static inline uint64\n pg_atomic_monotonic_advance_u64(volatile pg_atomic_uint64 *ptr, uint64 target_)\n {\n+\t/*\n+\t * When using actual (not simulated) atomics, the target variable for\n+\t * pg_atomic_compare_exchange_u64 must have suitable alignment, which\n+\t * is acquired naturally on most platforms, but not on 32-bit ones;\n+\t * persuade the compiler in that case, but fail if we\n+\t * cannot.\n+\t */\n+#if MAXIMUM_ALIGNOF >= 8\n \tuint64\t\tcurrval;\n+#elif defined(pg_attribute_aligned) && !defined(PG_HAVE_ATOMIC_U64_SIMULATION)\n+\tpg_attribute_aligned(8)\tuint64\t\tcurrval;\n+#else\n+#error \"Must have pg_attribute aligned or simulated atomics\"\n+#endif\n \n #ifndef PG_HAVE_ATOMIC_U64_SIMULATION\n \tAssertPointerAlignment(ptr, 8);\n\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/\n\"Just treat us the way you want to be treated + some extra allowance\n for ignorance.\" (Michael Brusser)\n\n\n", "msg_date": "Mon, 1 Jul 2024 16:54:51 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Alvaro Herrera <alvherre@alvh.no-ip.org> writes:\n> Maybe we can do something like this,\n\n> +#if MAXIMUM_ALIGNOF >= 8\n> \tuint64\t\tcurrval;\n\nThis should probably be testing the alignment of int64 specifically,\nrather than assuming that MAXIMUM_ALIGNOF applies to it. At least\nhistorically, there have been platforms where MAXIMUM_ALIGNOF is\ndetermined by float quantities and integer quantities are different.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 01 Jul 2024 10:59:18 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On 2024-Jul-01, Tom Lane wrote:\n\n> Alvaro Herrera <alvherre@alvh.no-ip.org> writes:\n> > Maybe we can do something like this,\n> \n> > +#if MAXIMUM_ALIGNOF >= 8\n> > \tuint64\t\tcurrval;\n> \n> This should probably be testing the alignment of int64 specifically,\n> rather than assuming that MAXIMUM_ALIGNOF applies to it. At least\n> historically, there have been platforms where MAXIMUM_ALIGNOF is\n> determined by float quantities and integer quantities are different.\n\nOK, so it's\n#if ALIGNOF_LONG_LONG_INT >= 8\n\nAlexander, can you please confirm whether this works for you?\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"La virtud es el justo medio entre dos defectos\" (Aristóteles)", "msg_date": "Mon, 1 Jul 2024 19:04:36 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Hi,\n\nOn 2024-07-01 11:10:24 +0200, Alvaro Herrera wrote:\n> In the meantime I noticed that pg_attribute_aligned() is not supported\n> in every platform/compiler, so for safety sake I think it's better to go\n> with what we do for PGAlignedBlock: use a union with a double member.\n> That should be 8-byte aligned on x86 as well, unless I misunderstand.\n\nIf a platform wants to support 8 byte atomics, it better provides a way to\nmake variables 8 bytes aligned. We already rely on that, actually. See use of\npg_attribute_aligned in e.g. src/include/port/atomics/generic-msvc.h\n\n\n\n> From 9d240e90f87bf8b53bd5d92b623e33419db64717 Mon Sep 17 00:00:00 2001\n> From: Alvaro Herrera <alvherre@alvh.no-ip.org>\n> Date: Mon, 1 Jul 2024 10:41:06 +0200\n> Subject: [PATCH v2] Fix alignment of variable in\n> pg_atomic_monotonic_advance_u64\n> \n> Reported-by: Alexander Lakhin <exclusion@gmail.com>\n> Discussion: https://postgr.es/m/36796438-a718-cf9b-2071-b2c1b947c1b5@gmail.com\n> ---\n> src/include/port/atomics.h | 24 ++++++++++++++++--------\n> 1 file changed, 16 insertions(+), 8 deletions(-)\n> \n> diff --git a/src/include/port/atomics.h b/src/include/port/atomics.h\n> index 78987f3154..964732e660 100644\n> --- a/src/include/port/atomics.h\n> +++ b/src/include/port/atomics.h\n> @@ -580,30 +580,38 @@ pg_atomic_sub_fetch_u64(volatile pg_atomic_uint64 *ptr, int64 sub_)\n> static inline uint64\n> pg_atomic_monotonic_advance_u64(volatile pg_atomic_uint64 *ptr, uint64 target_)\n> {\n> -\tuint64\t\tcurrval;\n> +\t/*\n> +\t * On 32-bit machines, declaring a bare uint64 variable doesn't promise\n> +\t * the alignment we need, so coerce the compiler this way.\n> +\t */\n> +\tunion\n> +\t{\n> +\t\tuint64\t\tu64;\n> +\t\tdouble\t\tforce_align_d;\n> +\t}\t\t\tcurrval;\n\nI wonder if we should just relax the alignment requirement for currval. It's\ncrucial that the pointer is atomically aligned (atomic ops across pages are\neither forbidden or extremely slow), but it's far from obvious that it's\ncrucial for comparator value to be aligned.\n\n\n> #ifndef PG_HAVE_ATOMIC_U64_SIMULATION\n> \tAssertPointerAlignment(ptr, 8);\n> #endif\n\nWhat's the point of this assert, btw? This stuff is already asserted in lower\nlevel routines, so it just seems redundant to have it here?\n\n\n> -\tcurrval = pg_atomic_read_u64_impl(ptr);\n> -\tif (currval >= target_)\n> +\tcurrval.u64 = pg_atomic_read_u64_impl(ptr);\n> +\tif (currval.u64 >= target_)\n> \t{\n> \t\tpg_memory_barrier();\n> -\t\treturn currval;\n> +\t\treturn currval.u64;\n> \t}\n> \n> #ifndef PG_HAVE_ATOMIC_U64_SIMULATION\n> -\tAssertPointerAlignment(&currval, 8);\n> +\tAssertPointerAlignment(&currval.u64, 8);\n> #endif\n> \n> -\twhile (currval < target_)\n> +\twhile (currval.u64 < target_)\n> \t{\n> -\t\tif (pg_atomic_compare_exchange_u64_impl(ptr, &currval, target_))\n> +\t\tif (pg_atomic_compare_exchange_u64_impl(ptr, &currval.u64, target_))\n> \t\t\tbreak;\n> \t}\n> \n> -\treturn Max(target_, currval);\n> +\treturn Max(target_, currval.u64);\n\nWhat does the Max() actually achieve here? Shouldn't it be impossible to reach\nthis with currval < target_?\n\nAnd why does target_ end in an underscore?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 1 Jul 2024 10:17:03 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Hello,\n\nThanks for your attention here.\n\nOn 2024-Jul-01, Andres Freund wrote:\n\n> On 2024-07-01 11:10:24 +0200, Alvaro Herrera wrote:\n> > In the meantime I noticed that pg_attribute_aligned() is not supported\n> > in every platform/compiler, so for safety sake I think it's better to go\n> > with what we do for PGAlignedBlock: use a union with a double member.\n> > That should be 8-byte aligned on x86 as well, unless I misunderstand.\n> \n> If a platform wants to support 8 byte atomics, it better provides a way to\n> make variables 8 bytes aligned. We already rely on that, actually. See use of\n> pg_attribute_aligned in e.g. src/include/port/atomics/generic-msvc.h\n\nWell, pg_atomic_uint64 is a struct. Passing pointers to it is fine,\nwhich is what non-platform-specific code does; but because the\ndeclaration of the type is in each platform-specific file, it might not\nwork to use it directly in generic code. I didn't actually try, but it\nseems a bit of a layering violation. (I didn't find any place where\nthe struct is used that way.)\n\nIf that works, then I think we could simply declare currval as a\npg_atomic_uint64 and it'd be prettier.\n\n> > +\t/*\n> > +\t * On 32-bit machines, declaring a bare uint64 variable doesn't promise\n> > +\t * the alignment we need, so coerce the compiler this way.\n> > +\t */\n> > +\tunion\n> > +\t{\n> > +\t\tuint64\t\tu64;\n> > +\t\tdouble\t\tforce_align_d;\n> > +\t}\t\t\tcurrval;\n> \n> I wonder if we should just relax the alignment requirement for currval. It's\n> crucial that the pointer is atomically aligned (atomic ops across pages are\n> either forbidden or extremely slow), but it's far from obvious that it's\n> crucial for comparator value to be aligned.\n\nI'm pretty sure the Microsoft docs I linked to are saying it must be\naligned.\n\n> > #ifndef PG_HAVE_ATOMIC_U64_SIMULATION\n> > \tAssertPointerAlignment(ptr, 8);\n> > #endif\n> \n> What's the point of this assert, btw? This stuff is already asserted in lower\n> level routines, so it just seems redundant to have it here?\n\nThere are in some of them, but not in pg_atomic_compare_exchange_u64_impl.\n\n\n> > -\treturn Max(target_, currval);\n> > +\treturn Max(target_, currval.u64);\n> \n> What does the Max() actually achieve here? Shouldn't it be impossible to reach\n> this with currval < target_?\n\nWhen two processes are hitting the cmpxchg concurrently, we need to\nreturn the highest value that was written, even if it was the other\nprocess that did it. The assertions in the calling site are quickly\nbroken if we don't do this. I admit this aspect took me by surprise.\n\n> And why does target_ end in an underscore?\n\nHeh, you tell me -- I just copied the style of the functions just above.\n\n-- \nÁlvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/\n\"No nos atrevemos a muchas cosas porque son difíciles,\npero son difíciles porque no nos atrevemos a hacerlas\" (Séneca)\n\n\n", "msg_date": "Mon, 1 Jul 2024 21:12:25 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "01.07.2024 20:04, Alvaro Herrera wrote:\n> OK, so it's\n> #if ALIGNOF_LONG_LONG_INT >= 8\n>\n> Alexander, can you please confirm whether this works for you?\n\nYes, the v4 patch makes `meson test --suite setup` pass in x86 environment.\nAnd complete `meson test` fails on pg_amcheck/004_verify_heapam only\n(I think it's a separate issue, just want to announce what else is broken\non that platform)\n\nThank you!\n\nBest regards,\nAlexander\n\n\n", "msg_date": "Tue, 2 Jul 2024 08:00:00 +0300", "msg_from": "Alexander Lakhin <exclusion@gmail.com>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On 2024-Jul-01, Alvaro Herrera wrote:\n\n> On 2024-Jul-01, Andres Freund wrote:\n> \n> > On 2024-07-01 11:10:24 +0200, Alvaro Herrera wrote:\n> > > In the meantime I noticed that pg_attribute_aligned() is not supported\n> > > in every platform/compiler, so for safety sake I think it's better to go\n> > > with what we do for PGAlignedBlock: use a union with a double member.\n> > > That should be 8-byte aligned on x86 as well, unless I misunderstand.\n> > \n> > If a platform wants to support 8 byte atomics, it better provides a way to\n> > make variables 8 bytes aligned. We already rely on that, actually. See use of\n> > pg_attribute_aligned in e.g. src/include/port/atomics/generic-msvc.h\n\nI noticed that all definitions have the value struct member named \"value\", so I\ngave this a quick try, and hit another issue: the \"expected\" argument of\npg_atomic_compare_exchange_u64_impl() is not volatile, which\npg_atomic_uint64.value is, so we get this warning:\n\nIn file included from /pgsql/source/master/src/include/storage/lwlock.h:21,\n from /pgsql/source/master/src/include/storage/lock.h:23,\n from /pgsql/source/master/src/include/access/twophase.h:20,\n from /pgsql/source/master/src/backend/access/transam/xlog.c:57:\n/pgsql/source/master/src/include/port/atomics.h: In function ‘pg_atomic_monotonic_advance_u64’:\n/pgsql/source/master/src/include/port/atomics.h:600:62: warning: passing argument 2 of ‘pg_atomic_compare_exchange_u64_impl’ discards ‘volatile’ qualifier from pointer target type [-Wdiscarded-qualifiers]\n 600 | if (pg_atomic_compare_exchange_u64_impl(ptr, &currval.value, target_))\n | ^~~~~~~~~~~~~~\nIn file included from /pgsql/source/master/src/include/port/atomics.h:69:\n/pgsql/source/master/src/include/port/atomics/arch-x86.h:206:81: note: expected ‘uint64 *’ {aka ‘long unsigned int *’} but argument is of type ‘volatile uint64 *’ {aka ‘volatile long unsigned int *’}\n 206 | uint64 *expected, uint64 newval)\n | ~~~~~~~~^~~~~~~~\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/\n\"Most hackers will be perfectly comfortable conceptualizing users as entropy\n sources, so let's move on.\" (Nathaniel Smith)\n https://mail.gnu.org/archive/html/monotone-devel/2007-01/msg00080.html\n\n\n", "msg_date": "Tue, 2 Jul 2024 13:55:49 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Hi,\n\nOn 2024-07-01 21:12:25 +0200, Alvaro Herrera wrote:\n> On 2024-Jul-01, Andres Freund wrote:\n> \n> > On 2024-07-01 11:10:24 +0200, Alvaro Herrera wrote:\n> > > In the meantime I noticed that pg_attribute_aligned() is not supported\n> > > in every platform/compiler, so for safety sake I think it's better to go\n> > > with what we do for PGAlignedBlock: use a union with a double member.\n> > > That should be 8-byte aligned on x86 as well, unless I misunderstand.\n> > \n> > If a platform wants to support 8 byte atomics, it better provides a way to\n> > make variables 8 bytes aligned. We already rely on that, actually. See use of\n> > pg_attribute_aligned in e.g. src/include/port/atomics/generic-msvc.h\n> \n> Well, pg_atomic_uint64 is a struct. Passing pointers to it is fine,\n> which is what non-platform-specific code does; but because the\n> declaration of the type is in each platform-specific file, it might not\n> work to use it directly in generic code. I didn't actually try, but it\n> seems a bit of a layering violation. (I didn't find any place where\n> the struct is used that way.)\n> \n> If that works, then I think we could simply declare currval as a\n> pg_atomic_uint64 and it'd be prettier.\n\nI don't think that'd make sense at all. The expected value isn't an atomic, so\nit shouldn't be the type of an atomic.\n\n\n> > > +\t/*\n> > > +\t * On 32-bit machines, declaring a bare uint64 variable doesn't promise\n> > > +\t * the alignment we need, so coerce the compiler this way.\n> > > +\t */\n> > > +\tunion\n> > > +\t{\n> > > +\t\tuint64\t\tu64;\n> > > +\t\tdouble\t\tforce_align_d;\n> > > +\t}\t\t\tcurrval;\n> > \n> > I wonder if we should just relax the alignment requirement for currval. It's\n> > crucial that the pointer is atomically aligned (atomic ops across pages are\n> > either forbidden or extremely slow), but it's far from obvious that it's\n> > crucial for comparator value to be aligned.\n> \n> I'm pretty sure the Microsoft docs I linked to are saying it must be\n> aligned.\n\nI don't think so:\nhttps://learn.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-interlockedcompareexchange64\n\nLONG64 InterlockedCompareExchange64(\n [in, out] LONG64 volatile *Destination,\n [in] LONG64 ExChange,\n [in] LONG64 Comperand\n);\n\nNote that Destination is the only argument passed by reference (and thus the\ncaller controls alignment of the in-memory value). ExChange is passed by\nvalue, so we don't control alignment in any way.\n\n\n> > > #ifndef PG_HAVE_ATOMIC_U64_SIMULATION\n> > > \tAssertPointerAlignment(ptr, 8);\n> > > #endif\n> > \n> > What's the point of this assert, btw? This stuff is already asserted in lower\n> > level routines, so it just seems redundant to have it here?\n> \n> There are in some of them, but not in pg_atomic_compare_exchange_u64_impl.\n\nBut there's one in pg_atomic_read_u64_impl(). But I actually think it's wrong\nfor pg_atomic_monotonic_advance_u64() to use _impl(), that's just for the\nwrapper functions around the implementation. Wheras\npg_atomic_monotonic_advance_u64() should just use the generic interface.\n\n\n> \n> > > -\treturn Max(target_, currval);\n> > > +\treturn Max(target_, currval.u64);\n> > \n> > What does the Max() actually achieve here? Shouldn't it be impossible to reach\n> > this with currval < target_?\n> \n> When two processes are hitting the cmpxchg concurrently, we need to\n> return the highest value that was written, even if it was the other\n> process that did it.\n\nSure. That explains needing to use currval. But not really needing to use\nMax(). If cmpxchg succeeds, we need to return target_, if the loop terminates\notherwise we need to return currval. No?\n\n\n\n> > And why does target_ end in an underscore?\n> \n> Heh, you tell me -- I just copied the style of the functions just above.\n\nIIRC using plain \"and\" \"or\" \"add\" caused conflicts with some headers or such.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 2 Jul 2024 05:17:59 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "On 2024-Jul-02, Andres Freund wrote:\n\n> On 2024-07-01 21:12:25 +0200, Alvaro Herrera wrote:\n> > On 2024-Jul-01, Andres Freund wrote:\n\n> > I'm pretty sure the Microsoft docs I linked to are saying it must be\n> > aligned.\n> \n> I don't think so:\n> https://learn.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-interlockedcompareexchange64\n> \n> LONG64 InterlockedCompareExchange64(\n> [in, out] LONG64 volatile *Destination,\n> [in] LONG64 ExChange,\n> [in] LONG64 Comperand\n> );\n> \n> Note that Destination is the only argument passed by reference (and thus the\n> caller controls alignment of the in-memory value). ExChange is passed by\n> value, so we don't control alignment in any way.\n\nHmm, you're right, assuming LONG64 is passed by value. Here\nhttps://learn.microsoft.com/en-us/windows/win32/winprog/windows-data-types\nit says that the type is declared as\ntypedef __int64 LONG64;\nand\nhttps://learn.microsoft.com/en-us/cpp/cpp/int8-int16-int32-int64?view=msvc-170\nsays that __int64 is a normal integer type. So yes, 'ExChange' is\npassed by value and therefore testing it for alignment is useless on\nthis platform.\n\n> > There are in some of them, but not in pg_atomic_compare_exchange_u64_impl.\n> \n> But there's one in pg_atomic_read_u64_impl(). \n\nSure, but pg_atomic_read_u64 is given 'ptr', not 'currval'.\n\n> But I actually think it's wrong for pg_atomic_monotonic_advance_u64()\n> to use _impl(), that's just for the wrapper functions around the\n> implementation. Wheras pg_atomic_monotonic_advance_u64() should just\n> use the generic interface.\n\nTrue. Well, I can remove the assertion from\npg_atomic_monotonic_advance_u64 and use pg_atomic_compare_exchange_u64\ninstead. But that one does this:\n\nstatic inline bool\npg_atomic_compare_exchange_u64(volatile pg_atomic_uint64 *ptr,\n uint64 *expected, uint64 newval)\n{\n#ifndef PG_HAVE_ATOMIC_U64_SIMULATION\n AssertPointerAlignment(ptr, 8);\n AssertPointerAlignment(expected, 8);\n#endif\n return pg_atomic_compare_exchange_u64_impl(ptr, expected, newval);\n}\n\n\nAFAICS this is still going to fail, because uint64 *expected comes from\nour &currval, which was not aligned before so it'll still be unaligned\nnow. The only difference is that the assertion failure will be in\npg_atomic_compare_exchange_u64 instead of in\npg_atomic_monotonic_advance_u64.\n\n\nOther platforms do have the 'expected' argument as a pointer, so the\nassertion there is not completely stupid. I think we could move the\nalignment assertions to appear inside the platform-specific _impl\nroutines that need it, and refrain from adding it to the MSVC one.\n\n\n> > > > -\treturn Max(target_, currval);\n> > > > +\treturn Max(target_, currval.u64);\n> > > \n> > > What does the Max() actually achieve here? Shouldn't it be impossible to reach\n> > > this with currval < target_?\n> > \n> > When two processes are hitting the cmpxchg concurrently, we need to\n> > return the highest value that was written, even if it was the other\n> > process that did it.\n> \n> Sure. That explains needing to use currval. But not really needing to use\n> Max(). If cmpxchg succeeds, we need to return target_, if the loop terminates\n> otherwise we need to return currval. No?\n\nOh, you're suggesting to change the break statement with a return.\nSeems reasonable.\n\n\n> > > And why does target_ end in an underscore?\n> > \n> > Heh, you tell me -- I just copied the style of the functions just above.\n> \n> IIRC using plain \"and\" \"or\" \"add\" caused conflicts with some headers or such.\n\nAh, that makes sense. It should be no problem to remove the underscore.\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/\n\"La primera ley de las demostraciones en vivo es: no trate de usar el sistema.\nEscriba un guión que no toque nada para no causar daños.\" (Jakob Nielsen)", "msg_date": "Tue, 2 Jul 2024 16:55:01 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" }, { "msg_contents": "Okay, so I've pushed the last version after confirming with Alexander\nthat it works on the Windows x86 machine. I hope nothing breaks now in\nthe buildfarm.\n\n-- \nÁlvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/\n\n\n", "msg_date": "Thu, 4 Jul 2024 13:36:40 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: LogwrtResult contended spinlock" } ]
[ { "msg_contents": "Per the discussion at [1], we're now aware of actual use-cases for\npassword strings approaching a kilobyte in length. I think this puts\nthe final nail in the coffin of the idea that passwordFromFile() can\nuse a fixed-length line buffer. Therefore, commit 2eb3bc588 (which\nadded a warning for overlength lines) seems rather misguided in\nhindsight. What we should do instead is fix that code so it has no\nhard upper bound on the line length. Even if you want to say that\nwe'll set a particular limit on how long the password field can be,\nthere's no good upper bound for the length of the hostname field;\nso ISTM that just getting out of the business of a fixed-size buffer\nis the sanest way.\n\nHence, the attached proposed patch does that, and for good measure\nadds some testing of this formerly untested code.\n\nSince we now have an actual user complaint, I'm inclined to back-patch\nthis all the way.\n\nAs noted in the other thread, there may be some other changes needed\nto support long passwords, but this is clearly required.\n\n\t\t\tregards, tom lane\n\n[1] https://www.postgresql.org/message-id/flat/CAOhmDze1nqG2vfegpSsTFCgaiFRsqgjO6yLsbmhroz2zGmJHog%40mail.gmail.com", "msg_date": "Mon, 31 Aug 2020 17:24:01 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Remove line length restriction in passwordFromFile()" }, { "msg_contents": "\n\nOn 2020/09/01 6:24, Tom Lane wrote:\n> Per the discussion at [1], we're now aware of actual use-cases for\n> password strings approaching a kilobyte in length. I think this puts\n> the final nail in the coffin of the idea that passwordFromFile() can\n> use a fixed-length line buffer. Therefore, commit 2eb3bc588 (which\n> added a warning for overlength lines) seems rather misguided in\n> hindsight. What we should do instead is fix that code so it has no\n> hard upper bound on the line length.\n\nAFAIR, there were proposals to increase the maximum length of password so far,\nbut we could not do that because we failed to get the consensus about\nthat change. But if we get the clear use-case requiring longer password and\nreach the consensus, that's good news. I agree with the change.\n\n> Even if you want to say that\n> we'll set a particular limit on how long the password field can be,\n> there's no good upper bound for the length of the hostname field;\n> so ISTM that just getting out of the business of a fixed-size buffer\n> is the sanest way.\n> \n> Hence, the attached proposed patch does that, and for good measure\n> adds some testing of this formerly untested code.\n> \n> Since we now have an actual user complaint, I'm inclined to back-patch\n> this all the way.\n> \n> As noted in the other thread, there may be some other changes needed\n> to support long passwords, but this is clearly required.\n\nYes, some client tools have 100 bytes length restriction for the password.\n\nRegards,\n\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Tue, 1 Sep 2020 10:00:38 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Remove line length restriction in passwordFromFile()" }, { "msg_contents": "\n\nOn 2020/09/01 10:00, Fujii Masao wrote:\n> \n> \n> On 2020/09/01 6:24, Tom Lane wrote:\n>> Per the discussion at [1], we're now aware of actual use-cases for\n>> password strings approaching a kilobyte in length.� I think this puts\n>> the final nail in the coffin of the idea that passwordFromFile() can\n>> use a fixed-length line buffer.� Therefore, commit 2eb3bc588 (which\n>> added a warning for overlength lines) seems rather misguided in\n>> hindsight.� What we should do instead is fix that code so it has no\n>> hard upper bound on the line length.\n> \n> AFAIR, there were proposals to increase the maximum length of password so far,\n> but we could not do that because we failed to get the consensus about\n> that change. But if we get the clear use-case requiring longer password and\n> reach the consensus, that's good news. I agree with the change.\n> \n>> Even if you want to say that\n>> we'll set a particular limit on how long the password field can be,\n>> there's no good upper bound for the length of the hostname field;\n>> so ISTM that just getting out of the business of a fixed-size buffer\n>> is the sanest way.\n>>\n>> Hence, the attached proposed patch does that, and for good measure\n>> adds some testing of this formerly untested code.\n\nThe patch looks good to me, except the following minor thing.\n\n+\t\tif (fgets(buf.data + buf.len, buf.maxlen - buf.len - 1, fp) == NULL)\n\nIIUC fgets() reads the data with the specified size - 1, so ISTM that -1 of\n\"buf.maxlen - buf.len - 1\" is not necessary.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Tue, 1 Sep 2020 14:41:09 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Remove line length restriction in passwordFromFile()" }, { "msg_contents": "Fujii Masao <masao.fujii@oss.nttdata.com> writes:\n> The patch looks good to me, except the following minor thing.\n> +\t\tif (fgets(buf.data + buf.len, buf.maxlen - buf.len - 1, fp) == NULL)\n> IIUC fgets() reads the data with the specified size - 1, so ISTM that -1 of\n> \"buf.maxlen - buf.len - 1\" is not necessary.\n\nGood point, I was being unduly conservative. Thanks for reviewing\nthe patch!\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 01 Sep 2020 11:14:47 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Remove line length restriction in passwordFromFile()" }, { "msg_contents": "\n\nOn 2020/09/02 0:14, Tom Lane wrote:\n> Fujii Masao <masao.fujii@oss.nttdata.com> writes:\n>> The patch looks good to me, except the following minor thing.\n>> +\t\tif (fgets(buf.data + buf.len, buf.maxlen - buf.len - 1, fp) == NULL)\n>> IIUC fgets() reads the data with the specified size - 1, so ISTM that -1 of\n>> \"buf.maxlen - buf.len - 1\" is not necessary.\n> \n> Good point, I was being unduly conservative. Thanks for reviewing\n> the patch!\n\nThanks for committing the patch!\n\nThe patch was back-patched to v13, but v13 release note still has the following item.\n\n Tighten libpq's overlength-line handling and comment detection for .pgpass files (Fujii Masao)\n\nThis should be changed to the following or something?\n\n Teach libpq to handle arbitrary-length lines in .pgpass files (Tom Lane)\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 10 Sep 2020 01:34:48 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Remove line length restriction in passwordFromFile()" }, { "msg_contents": "Fujii Masao <masao.fujii@oss.nttdata.com> writes:\n> The patch was back-patched to v13, but v13 release note still has the following item.\n\n> Tighten libpq's overlength-line handling and comment detection for .pgpass files (Fujii Masao)\n\n> This should be changed to the following or something?\n\n> Teach libpq to handle arbitrary-length lines in .pgpass files (Tom Lane)\n\nHm. Actually, since that went further back than v13, I don't think\nit should appear in the v13 notes at all; it will be material for\nthe next quarterly update release notes.\n\nWe could adjust the release-note entry for your patch to say\n\"Improve comment detection for .pgpass files\", or we could decide\nit's not worth documenting that part and just drop the entry.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 09 Sep 2020 12:48:17 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Remove line length restriction in passwordFromFile()" }, { "msg_contents": "\n\nOn 2020/09/10 1:48, Tom Lane wrote:\n> Fujii Masao <masao.fujii@oss.nttdata.com> writes:\n>> The patch was back-patched to v13, but v13 release note still has the following item.\n> \n>> Tighten libpq's overlength-line handling and comment detection for .pgpass files (Fujii Masao)\n> \n>> This should be changed to the following or something?\n> \n>> Teach libpq to handle arbitrary-length lines in .pgpass files (Tom Lane)\n> \n> Hm. Actually, since that went further back than v13, I don't think\n> it should appear in the v13 notes at all; it will be material for\n> the next quarterly update release notes.\n> \n> We could adjust the release-note entry for your patch to say\n> \"Improve comment detection for .pgpass files\", or we could decide\n> it's not worth documenting that part and just drop the entry.\n\n\"Improve comment detection for .pgpass files\" is also the material for\nminor version release because that change was also back-patched?\nIf so, I agree to drop the entry.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 10 Sep 2020 02:00:15 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Remove line length restriction in passwordFromFile()" }, { "msg_contents": "Fujii Masao <masao.fujii@oss.nttdata.com> writes:\n> On 2020/09/10 1:48, Tom Lane wrote:\n>> We could adjust the release-note entry for your patch to say\n>> \"Improve comment detection for .pgpass files\", or we could decide\n>> it's not worth documenting that part and just drop the entry.\n\n> \"Improve comment detection for .pgpass files\" is also the material for\n> minor version release because that change was also back-patched?\n> If so, I agree to drop the entry.\n\nHm, in a quick search I only see 2eb3bc588 which was not back-patched\n... which commits are you thinking of?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 09 Sep 2020 13:16:33 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Remove line length restriction in passwordFromFile()" }, { "msg_contents": "\n\nOn 2020/09/10 2:16, Tom Lane wrote:\n> Fujii Masao <masao.fujii@oss.nttdata.com> writes:\n>> On 2020/09/10 1:48, Tom Lane wrote:\n>>> We could adjust the release-note entry for your patch to say\n>>> \"Improve comment detection for .pgpass files\", or we could decide\n>>> it's not worth documenting that part and just drop the entry.\n> \n>> \"Improve comment detection for .pgpass files\" is also the material for\n>> minor version release because that change was also back-patched?\n>> If so, I agree to drop the entry.\n> \n> Hm, in a quick search I only see 2eb3bc588 which was not back-patched\n> ... which commits are you thinking of?\n\nI thought your commit b55b4dad99 included the improvement on comment detection and was back-patched....\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 10 Sep 2020 03:20:54 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Remove line length restriction in passwordFromFile()" }, { "msg_contents": "Fujii Masao <masao.fujii@oss.nttdata.com> writes:\n> On 2020/09/10 2:16, Tom Lane wrote:\n>> Hm, in a quick search I only see 2eb3bc588 which was not back-patched\n>> ... which commits are you thinking of?\n\n> I thought your commit b55b4dad99 included the improvement on comment detection and was back-patched....\n\nOh, right, I did include the check for '#' in what was back-patched.\nI debated whether to do that or not, and was misremembering my decision.\n\nSo yeah, it seems there's no need to document 2eb3bc588 in the v13\nnotes. I'll try to remember to give you part credit for b55b4dad9\nwhen I do the November notes.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 09 Sep 2020 14:29:16 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Remove line length restriction in passwordFromFile()" } ]
[ { "msg_contents": "Hi hackers,\r\n\r\nAs described in the doc https://www.postgresql.org/docs/current/sql-copy.html, the TEXT format recognizes\r\nbackslash-period (\\.) as end-of-data marker.\r\n\r\nThe example below will raise an error for the line contains `\\.`.\r\n\r\nCREATE TABLE test (\r\nid int,\r\nname text,\r\ndep text\r\n)\r\n\r\nData in file \"/tmp/data\".\r\n\r\n122,as\\.d,adad\r\n133,sa dad,adadad\r\n\r\nThen execute\r\n\r\ncopy test from '/tmp/data' DELIMITER ',';\r\n\r\nAn end-of-copy marker corrupt error will be raised.\r\n\r\nThis requires users to escape the end-of-data marker manually in their data.\r\nWhy we don't have a mechanism to define other characters as end-of-data marker?\r\nOr there are other ways to avoid escape the end-of-data in data?\r\n\r\nRegards,\r\nJunfeng\r\n\r\n\r\n\n\n\n\n\n\n\n\nHi hackers,\n\n\n\n\nAs described in the doc https://www.postgresql.org/docs/current/sql-copy.html, the TEXT format recognizes\n\nbackslash-period (\\.) as end-of-data marker.\n\n\n\n\nThe example below will raise an error for the line contains `\\.`.\n\nCREATE TABLE test (\nid int,\nname text,\ndep text\n)\n\n\nData in file \"/tmp/data\".\n\n122,as\\.d,adad\n133,sa dad,adadad\nThen execute\n\ncopy test from '/tmp/data' DELIMITER ',';\nAn \nend-of-copy marker corrupt error will be raised.\n\n\n\n\nThis requires users to escape the end-of-data marker manually in their data.\n\nWhy we don't have a mechanism to define other characters as end-of-data marker?\n\nOr there are other ways to avoid escape the end-of-data in data?\n\n\n\n\nRegards,\n\nJunfeng", "msg_date": "Tue, 1 Sep 2020 06:14:45 +0000", "msg_from": "Junfeng Yang <yjerome@vmware.com>", "msg_from_op": true, "msg_subject": "Is it possible to set end-of-data marker for COPY statement." }, { "msg_contents": "[redirected from -hackers]\nOn Tue, 2020-09-01 at 06:14 +0000, Junfeng Yang wrote:\n> As described in the doc https://www.postgresql.org/docs/current/sql-copy.html, the TEXT format recognizes\n> backslash-period (\\.) as end-of-data marker.\n> \n> The example below will raise an error for the line contains `\\.`.\n> CREATE TABLE test (\n> id int,\n> name text,\n> dep text\n> )\n>\n> Data in file \"/tmp/data\".\n>\n> 122,as\\.d,adad\n> 133,sa dad,adadad\n> Then execute\n> copy test from '/tmp/data' DELIMITER ',';\n> An end-of-copy marker corrupt error will be raised.\n> \n> This requires users to escape the end-of-data marker manually in their data.\n> Why we don't have a mechanism to define other characters as end-of-data marker?\n> Or there are other ways to avoid escape the end-of-data in data?\n\nYour problem is that the file contains bad data.\n\nYou are using the default TEXT format of copy, and backslashes must\nbe escaped there.\n\nEverything will work as you want if you write the first line correctly like\n\n122,as\\\\.d,adad\n\nYours,\nLaurenz Albe\n-- \nCybertec | https://www.cybertec-postgresql.com\n\n\n\n", "msg_date": "Tue, 01 Sep 2020 11:06:00 +0200", "msg_from": "Laurenz Albe <laurenz.albe@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: Is it possible to set end-of-data marker for COPY statement." }, { "msg_contents": "Thanks, Laurenz!\r\n\r\nI understand `\\\\.` should work. But this requires users to modify huge data.\r\nI'm wondering is it possible to change the default end-of-data marker or\r\ncould we implement a method to let users choose their own marker?\r\n________________________________\r\n发件人: Laurenz Albe <laurenz.albe@cybertec.at>\r\n发送时间: 2020年9月1日 17:06\r\n收件人: Junfeng Yang <yjerome@vmware.com>; pgsql-general@postgresql.org <pgsql-general@postgresql.org>\r\n主题: Re: Is it possible to set end-of-data marker for COPY statement.\r\n\r\n[redirected from -hackers]\r\nOn Tue, 2020-09-01 at 06:14 +0000, Junfeng Yang wrote:\r\n> As described in the doc https://nam04.safelinks.protection.outlook.com/?url=https%3A%2F%2Fwww.postgresql.org%2Fdocs%2Fcurrent%2Fsql-copy.html&amp;data=02%7C01%7Cyjerome%40vmware.com%7Cd75fda5803f54dcd9dc408d84e5640d7%7Cb39138ca3cee4b4aa4d6cd83d9dd62f0%7C0%7C0%7C637345479659888992&amp;sdata=CyY%2FAwPTB%2Bl3qMZbcxts5zKrW1QOiqL5%2Ft8MSEuaQk4%3D&amp;reserved=0, the TEXT format recognizes\r\n> backslash-period (\\.) as end-of-data marker.\r\n>\r\n> The example below will raise an error for the line contains `\\.`.\r\n> CREATE TABLE test (\r\n> id int,\r\n> name text,\r\n> dep text\r\n> )\r\n>\r\n> Data in file \"/tmp/data\".\r\n>\r\n> 122,as\\.d,adad\r\n> 133,sa dad,adadad\r\n> Then execute\r\n> copy test from '/tmp/data' DELIMITER ',';\r\n> An end-of-copy marker corrupt error will be raised.\r\n>\r\n> This requires users to escape the end-of-data marker manually in their data.\r\n> Why we don't have a mechanism to define other characters as end-of-data marker?\r\n> Or there are other ways to avoid escape the end-of-data in data?\r\n\r\nYour problem is that the file contains bad data.\r\n\r\nYou are using the default TEXT format of copy, and backslashes must\r\nbe escaped there.\r\n\r\nEverything will work as you want if you write the first line correctly like\r\n\r\n122,as\\\\.d,adad\r\n\r\nYours,\r\nLaurenz Albe\r\n--\r\nCybertec | https://nam04.safelinks.protection.outlook.com/?url=https%3A%2F%2Fwww.cybertec-postgresql.com%2F&amp;data=02%7C01%7Cyjerome%40vmware.com%7Cd75fda5803f54dcd9dc408d84e5640d7%7Cb39138ca3cee4b4aa4d6cd83d9dd62f0%7C0%7C0%7C637345479659888992&amp;sdata=Q3lepnqcPJnJW9LPDCdXOyoejUf1mBsbovNWPMxhQ4g%3D&amp;reserved=0\r\n\r\n\n\n\n\n\n\n\n\nThanks, Laurenz!\n\n\n\n\nI understand `\\\\.` should work. But this requires users to modify huge data.\n\nI'm wondering is it possible to change the default end-of-data marker or\n\ncould we implement a method to let users choose their own marker?\n\n\n发件人: Laurenz Albe <laurenz.albe@cybertec.at>\n发送时间: 2020年9月1日 17:06\n收件人: Junfeng Yang <yjerome@vmware.com>; pgsql-general@postgresql.org <pgsql-general@postgresql.org>\n主题: Re: Is it possible to set end-of-data marker for COPY statement.\n \n\n\n[redirected from -hackers]\nOn Tue, 2020-09-01 at 06:14 +0000, Junfeng Yang wrote:\n> As described in the doc \nhttps://nam04.safelinks.protection.outlook.com/?url=https%3A%2F%2Fwww.postgresql.org%2Fdocs%2Fcurrent%2Fsql-copy.html&amp;data=02%7C01%7Cyjerome%40vmware.com%7Cd75fda5803f54dcd9dc408d84e5640d7%7Cb39138ca3cee4b4aa4d6cd83d9dd62f0%7C0%7C0%7C637345479659888992&amp;sdata=CyY%2FAwPTB%2Bl3qMZbcxts5zKrW1QOiqL5%2Ft8MSEuaQk4%3D&amp;reserved=0,\n the TEXT format recognizes\n> backslash-period (\\.) as end-of-data marker.\n> \n> The example below will raise an error for the line contains `\\.`.\n> CREATE TABLE test (\n> id int,\n> name text,\n> dep text\n> )\n>\n> Data in file \"/tmp/data\".\n>\n> 122,as\\.d,adad\n> 133,sa dad,adadad\n> Then execute\n> copy test from '/tmp/data' DELIMITER ',';\n> An end-of-copy marker corrupt error will be raised.\n> \n> This requires users to escape the end-of-data marker manually in their data.\n> Why we don't have a mechanism to define other characters as end-of-data marker?\n> Or there are other ways to avoid escape the end-of-data in data?\n\nYour problem is that the file contains bad data.\n\nYou are using the default TEXT format of copy, and backslashes must\nbe escaped there.\n\nEverything will work as you want if you write the first line correctly like\n\n122,as\\\\.d,adad\n\nYours,\nLaurenz Albe\n-- \nCybertec | \nhttps://nam04.safelinks.protection.outlook.com/?url=https%3A%2F%2Fwww.cybertec-postgresql.com%2F&amp;data=02%7C01%7Cyjerome%40vmware.com%7Cd75fda5803f54dcd9dc408d84e5640d7%7Cb39138ca3cee4b4aa4d6cd83d9dd62f0%7C0%7C0%7C637345479659888992&amp;sdata=Q3lepnqcPJnJW9LPDCdXOyoejUf1mBsbovNWPMxhQ4g%3D&amp;reserved=0", "msg_date": "Tue, 1 Sep 2020 09:20:00 +0000", "msg_from": "Junfeng Yang <yjerome@vmware.com>", "msg_from_op": true, "msg_subject": "\n =?gb2312?B?u9i4tDogSXMgaXQgcG9zc2libGUgdG8gc2V0IGVuZC1vZi1kYXRhIG1hcmtl?=\n =?gb2312?Q?r_for_COPY_statement.?=" }, { "msg_contents": "Please, don't top-post on these lists.\n\nOn Tue, 2020-09-01 at 09:20 +0000, Junfeng Yang wrote:\n> \n> 发件人: Laurenz Albe <laurenz.albe@cybertec.at>\n> > On Tue, 2020-09-01 at 06:14 +0000, Junfeng Yang wrote:\n> > > As described in the doc , the TEXT format recognizes\n> > > backslash-period (\\.) as end-of-data marker.\n> > >\n> > > The example below will raise an error for the line contains `\\.`.\n> > >\n> > > CREATE TABLE test (\n> > > id int,\n> > > name text,\n> > > dep text\n> > > )\n> > >\n> > > Data in file \"/tmp/data\".\n> > >\n> > > 122,as\\.d,adad\n> > > 133,sa dad,adadad\n> > > Then execute\n> > > copy test from '/tmp/data' DELIMITER ',';\n> > > An end-of-copy marker corrupt error will be raised.\n> > >\n> > > This requires users to escape the end-of-data marker manually in their data.\n> > > Why we don't have a mechanism to define other characters as end-of-data marker?\n> > > Or there are other ways to avoid escape the end-of-data in data?\n> >\n> > Your problem is that the file contains bad data.\n> >\n> > You are using the default TEXT format of copy, and backslashes must\n> > be escaped there.\n> >\n> > Everything will work as you want if you write the first line correctly like\n> >\n> > 122,as\\\\.d,adad\n>\n> I understand `\\\\.` should work. But this requires users to modify huge data.\n> I'm wondering is it possible to change the default end-of-data marker or\n> could we implement a method to let users choose their own marker?\n\nI don't see the problem.\n\nIf you use the CSV format, your data will work fine the way they are:\n\n COPY test FROM '/tmp/data' (FORMAT 'csv');\n\nYours,\nLaurenz Albe\n-- \nCybertec | https://www.cybertec-postgresql.com\n\n\n\n", "msg_date": "Tue, 01 Sep 2020 11:37:38 +0200", "msg_from": "Laurenz Albe <laurenz.albe@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: =?UTF-8?Q?=E5=9B=9E=E5=A4=8D=3A?= Is it possible to set\n end-of-data marker for COPY statement." }, { "msg_contents": "Thanks for your response!\r\n\n\n\n\n\n\n\n\nThanks for your response!", "msg_date": "Tue, 1 Sep 2020 10:03:35 +0000", "msg_from": "Junfeng Yang <yjerome@vmware.com>", "msg_from_op": true, "msg_subject": "\n =?gb2312?B?u9i4tDogu9i4tDogSXMgaXQgcG9zc2libGUgdG8gc2V0IGVuZC1vZi1kYXRh?=\n =?gb2312?Q?_marker_for_COPY_statement.?=" }, { "msg_contents": "On Tue, Sep 1, 2020 at 06:14:45AM +0000, Junfeng Yang wrote:\n> Hi hackers,\n> \n> As described in the doc https://www.postgresql.org/docs/current/sql-copy.html,\n> the TEXT format recognizes\n> backslash-period (\\.) as end-of-data marker.\n> \n> The example below will raise an error for the line contains `\\.`.\n> \n> CREATE TABLE test (\n> id int,\n> name text,\n> dep text\n> )\n> \n> Data in file \"/tmp/data\".\n> \n> 122,as\\.d,adad\n> 133,sa dad,adadad\n> \n> Then execute\n> \n> copy test from '/tmp/data' DELIMITER ',';\n> \n> An end-of-copy marker corrupt error will be raised.\n> \n> This requires users to escape the end-of-data marker manually in their data.\n> Why we don't have a mechanism to define other characters as end-of-data marker?\n> Or there are other ways to avoid escape the end-of-data in data?\n\nThis is the first I am hearing of this. The problem is that the system\ncan't decide if \\. is escaping a delimiter, or the end-of-copy marker. \nI think we need to just disable period as a delimiter. I don't think\nthere is enough demand to allow the end-of-data marker to be\nconfigurable.\n\nInterestingly, you can use period as s delimiter if you are copying from\na file that doesn't need an end-of-data marker and you never need to\nescape the delimiter, but that seems like too rare a use case to allow\nperiod to be supported as a delimiter.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Tue, 1 Sep 2020 12:05:02 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Is it possible to set end-of-data marker for COPY statement." }, { "msg_contents": "On Tue, Sep 1, 2020 at 9:05 AM Bruce Momjian <bruce@momjian.us> wrote:\n\n> On Tue, Sep 1, 2020 at 06:14:45AM +0000, Junfeng Yang wrote:\n> > Hi hackers,\n> >\n>\n> > Data in file \"/tmp/data\".\n> >\n> > 122,as\\.d,adad\n> > 133,sa dad,adadad\n> >\n> > Then execute\n> >\n> > copy test from '/tmp/data' DELIMITER ',';\n> >\n> > An end-of-copy marker corrupt error will be raised.\n>\n> This is the first I am hearing of this. The problem is that the system\n> can't decide if \\. is escaping a delimiter, or the end-of-copy marker.\n> I think we need to just disable period as a delimiter. I don't think\n> there is enough demand to allow the end-of-data marker to be\n> configurable.\n>\n> Interestingly, you can use period as s delimiter if you are copying from\n> a file that doesn't need an end-of-data marker and you never need to\n> escape the delimiter, but that seems like too rare a use case to allow\n> period to be supported as a delimiter.\n>\n\nSomething isn't right here because the rules for end-of-copy are explicit\nthat the \\. must appear on a line all by itself. That isn't the case with\nthe shown test data.\n\nThe system should do one of two things with that input (it seems option 2\nis the one we've chosen):\n\nOne, see that the character following the backslash is not an action\ncharacter and just treat the backslash as data.\nTwo, complain that the character following the backslash is not a valid\naction character.\n\nThe system is reporting an error, it's just trying to be helpful and seeing\nthe period it incorrectly reports that the error has something to do with\nthe end-of-copy marker when in reality all that can be said is that \"a\nperiod in this location is not valid\" (unless the command uses DELIMITER\n'<period>' at least, in which case the period is now valid and \\. means a\nliteral period since its not alone on a line.)\n\nThe only limitation our definition of end-of-copy imposes is that a single\ncolumn input file cannot contain a record that is only a period. It does\nnot impose a limitation on which delimiters are valid.\n\nDavid J.\n\nOn Tue, Sep 1, 2020 at 9:05 AM Bruce Momjian <bruce@momjian.us> wrote:On Tue, Sep  1, 2020 at 06:14:45AM +0000, Junfeng Yang wrote:\n> Hi hackers,\n> \n> Data in file \"/tmp/data\".\n> \n> 122,as\\.d,adad\n> 133,sa dad,adadad\n> \n> Then execute\n> \n> copy test from '/tmp/data' DELIMITER ',';\n> \n> An end-of-copy marker corrupt error will be raised.\nThis is the first I am hearing of this.  The problem is that the system\ncan't decide if \\. is escaping a delimiter, or the end-of-copy marker. \nI think we need to just disable period as a delimiter.  I don't think\nthere is enough demand to allow the end-of-data marker to be\nconfigurable.\n\nInterestingly, you can use period as s delimiter if you are copying from\na file that doesn't need an end-of-data marker and you never need to\nescape the delimiter, but that seems like too rare a use case to allow\nperiod to be supported as a delimiter.Something isn't right here because the rules for end-of-copy are explicit that the \\. must appear on a line all by itself.  That isn't the case with the shown test data.The system should do one of two things with that input (it seems option 2 is the one we've chosen):One, see that the character following the backslash is not an action character and just treat the backslash as data.Two, complain that the character following the backslash is not a valid action character.The system is reporting an error, it's just trying to be helpful and seeing the period it incorrectly reports that the error has something to do with the end-of-copy marker when in reality all that can be said is that \"a period in this location is not valid\" (unless the command uses DELIMITER '<period>' at least, in which case the period is now valid and \\. means a literal period since its not alone on a line.)The only limitation our definition of end-of-copy imposes is that a single column input file cannot contain a record that is only a period.  It does not impose a limitation on which delimiters are valid.David J.", "msg_date": "Tue, 1 Sep 2020 09:30:30 -0700", "msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Is it possible to set end-of-data marker for COPY statement." }, { "msg_contents": "On Tue, Sep 1, 2020 at 12:05:02PM -0400, Bruce Momjian wrote:\n> > copy test from '/tmp/data' DELIMITER ',';\n> > \n> > An end-of-copy marker corrupt error will be raised.\n> > \n> > This requires users to escape the end-of-data marker manually in their data.\n> > Why we don't have a mechanism to define other characters as end-of-data marker?\n> > Or there are other ways to avoid escape the end-of-data in data?\n> \n> This is the first I am hearing of this. The problem is that the system\n> can't decide if \\. is escaping a delimiter, or the end-of-copy marker. \n> I think we need to just disable period as a delimiter. I don't think\n> there is enough demand to allow the end-of-data marker to be\n> configurable.\n> \n> Interestingly, you can use period as s delimiter if you are copying from\n> a file that doesn't need an end-of-data marker and you never need to\n> escape the delimiter, but that seems like too rare a use case to allow\n> period to be supported as a delimiter.\n\nI am sorry I mis-read this email. The example uses _comma_ for the\ndelimiter, rather than period. Let me reply again. We already disallow\nperiod for delimiters:\n\n COPY test TO '/u/postgres/tmp/x' WITH (DELIMITER '.');\n ERROR: COPY delimiter cannot be \".\"\n\n COPY test TO STDOUT WITH (DELIMITER '.');\n ERROR: COPY delimiter cannot be \".\"\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Tue, 1 Sep 2020 13:23:00 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Is it possible to set end-of-data marker for COPY statement." }, { "msg_contents": "On Tue, Sep 1, 2020 at 06:14:45AM +0000, Junfeng Yang wrote:\n> Hi hackers,\n> \n> As described in the doc https://www.postgresql.org/docs/current/sql-copy.html,\n> the TEXT format recognizes\n> backslash-period (\\.) as end-of-data marker.\n> \n> The example below will raise an error for the line contains `\\.`.\n> \n> CREATE TABLE test (\n> id int,\n> name text,\n> dep text\n> )\n> \n> Data in file \"/tmp/data\".\n> \n> 122,as\\.d,adad\n> 133,sa dad,adadad\n> \n> Then execute\n> \n> copy test from '/tmp/data' DELIMITER ',';\n> \n> An end-of-copy marker corrupt error will be raised.\n> \n> This requires users to escape the end-of-data marker manually in their data.\n> Why we don't have a mechanism to define other characters as end-of-data marker?\n> Or there are other ways to avoid escape the end-of-data in data?\n\nSo, you are using comma as the delimiter, but have \\. (backslash-period)\nas a data value. You need to double-up backslashes in your input data,\nno matter what is after the backslash. You just happen to hit backslash\nperiod, but other things like \\N could cause problems --- literal\nbackslashes have to be doubled.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Tue, 1 Sep 2020 13:25:50 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Is it possible to set end-of-data marker for COPY statement." }, { "msg_contents": "Bruce Momjian <bruce@momjian.us> writes:\n> On Tue, Sep 1, 2020 at 06:14:45AM +0000, Junfeng Yang wrote:\n>> Data in file \"/tmp/data\".\n>> \n>> 122,as\\.d,adad\n>> 133,sa dad,adadad\n\n> So, you are using comma as the delimiter, but have \\. (backslash-period)\n> as a data value. You need to double-up backslashes in your input data,\n> no matter what is after the backslash. You just happen to hit backslash\n> period, but other things like \\N could cause problems --- literal\n> backslashes have to be doubled.\n\nAs mentioned upthread, using CSV format might work better. In CSV\nyou aren't necessarily stuck with backslash being treated as an\nescape character.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 01 Sep 2020 14:01:06 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Is it possible to set end-of-data marker for COPY statement." }, { "msg_contents": "Thanks for all your feedbacks!\r\n\n\n\n\n\n\n\n\nThanks for all your feedbacks!", "msg_date": "Tue, 8 Sep 2020 01:53:26 +0000", "msg_from": "Junfeng Yang <yjerome@vmware.com>", "msg_from_op": true, "msg_subject": "\n =?gb2312?B?u9i4tDogSXMgaXQgcG9zc2libGUgdG8gc2V0IGVuZC1vZi1kYXRhIG1hcmtl?=\n =?gb2312?Q?r_for_COPY_statement.?=" } ]
[ { "msg_contents": "A custom table access method might want to add a new reloption to\ncontrol something specific to that table access method. Unfortunately,\nif you add a new option of type RELOPT_KIND_HEAP, it will immediately\nfail because of the validation that happens in fillRelOptions().\n\nRight now, heap reloptions (e.g. FILLFACTOR) are validated in two\nplaces: parseRelOptions() and fillRelOptions().\n\nparseRelOptions() validates against boolRelOpts[], intRelOpts[], etc.\nThis validation is extensible by add_bool_reloption(), etc.\n\nfillRelOptions() validates when filling in a struct to make sure there\naren't \"leftover\" options. It does this using a hard-coded parsing\ntable that is not extensible.\n\nIndex access methods get total control over validation of reloptions,\nbut that doesn't fit well with heaps, because all heaps need the\nvacuum-related options.\n\nI considered some other approaches, but they all seemed like over-\nengineering, so the attached patch just passes validate=false to\nfillRelOptions() for heaps. That allows custom table access methods to\njust define new options of kind RELOPT_KIND_HEAP.\n\nRegards,\n\tJeff Davis", "msg_date": "Mon, 31 Aug 2020 23:18:39 -0700", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": true, "msg_subject": "Reloptions for table access methods" }, { "msg_contents": "\n\n\n\n\n‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn Tuesday, 1 September 2020 09:18, Jeff Davis <pgsql@j-davis.com> wrote:\n\n> A custom table access method might want to add a new reloption to\n> control something specific to that table access method. Unfortunately,\n> if you add a new option of type RELOPT_KIND_HEAP, it will immediately\n> fail because of the validation that happens in fillRelOptions().\n>\n> Right now, heap reloptions (e.g. FILLFACTOR) are validated in two\n> places: parseRelOptions() and fillRelOptions().\n>\n> parseRelOptions() validates against boolRelOpts[], intRelOpts[], etc.\n> This validation is extensible by add_bool_reloption(), etc.\n>\n> fillRelOptions() validates when filling in a struct to make sure there\n> aren't \"leftover\" options. It does this using a hard-coded parsing\n> table that is not extensible.\n>\n> Index access methods get total control over validation of reloptions,\n> but that doesn't fit well with heaps, because all heaps need the\n> vacuum-related options.\n>\n> I considered some other approaches, but they all seemed like over-\n> engineering, so the attached patch just passes validate=false to\n> fillRelOptions() for heaps. That allows custom table access methods to\n> just define new options of kind RELOPT_KIND_HEAP.\n\nI have yet to look at the diff. I simply wanted to give you my wholehearted +1 to the idea. It is a necessary and an essential part of developing access methods.\n\nI have worked extensively in the merge of PG12 into Greenplum, with a focus to the tableam api. Handling reloptions has been quite a pain to do cleanly. Given the nature of Greenplum's table access methods, we were forced to take it a couple of steps further. We did use an approach which I am certain that you have considered and discarded as over-engineering for postgres.\n\nIn short, I am really excited to see a patch for this topic!\n\n>\n> Regards,\n> Jeff Davis\n\n\n\n\n", "msg_date": "Tue, 01 Sep 2020 10:36:51 +0000", "msg_from": "gkokolatos@pm.me", "msg_from_op": false, "msg_subject": "Re: Reloptions for table access methods" }, { "msg_contents": "On 2020-Aug-31, Jeff Davis wrote:\n\n> fillRelOptions() validates when filling in a struct to make sure there\n> aren't \"leftover\" options. It does this using a hard-coded parsing\n> table that is not extensible.\n\nHmm, I think that if we're going to do this, we should do it for all\nAMs, not just table AMs, since surely index AMs also want extensible\nreloptions; and I think that makes the 'validate' mechanism dead code\nand so we should remove it.\n\nI think this means that you can have tables with mistyped options, and\nyou'd not get an error message about them. Is that right? Is that what\nwe want?\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 1 Sep 2020 12:20:08 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Reloptions for table access methods" }, { "msg_contents": "On Tue, 2020-09-01 at 12:20 -0400, Alvaro Herrera wrote:\n> Hmm, I think that if we're going to do this, we should do it for all\n> AMs, not just table AMs, since surely index AMs also want extensible\n> reloptions; and I think that makes the 'validate' mechanism dead code\n> and so we should remove it.\n\nIndex AMs totally control the validation, so as they add options with\nadd_bool_reloption, they can also add to their custom parsing table.\n\nI'm fine removing the \"validate\" parameter completely for the sake of\nconsistency.\n\n> I think this means that you can have tables with mistyped options,\n> and\n> you'd not get an error message about them. Is that right? Is that\n> what\n> we want?\n\nNo, mistyped options (e.g. \"fillfactory=50\") will still cause an error,\nbecause there are two layers of validation.\n\nThe problem case would be a situation like the following:\n\n1. Someone loads an extension that creates a new reloption\n\"custom_reloption\" of kind RELOPT_KIND_HEAP for their table access\nmethod \"my_tableam\". \n\n2. They then create a table and forget to specify \"USING my_tableam\",\nbut use the option \"custom_reloption=123\".\n\nIdeally, that would throw an error because \"custom_reloption\" is only\nvalid for \"my_tableam\"; but with my patch, no error would be thrown\nbecause the extension has already added the reloption. It would just\ncreate a normal heap and \"custom_reloption=123\" would be ignored.\n\n\n\nI went with the simple approach because fixing that problem seemed a\nbit over-engineered. Here are some thoughts on what we could do:\n\n* Consider StdRdOptions to be an extensible struct (where postgres just\nlooks at the StdRdOptions fields, but the extension can cast it to the\nmore specialized struct with extra fields). This is awkward, because\nit's not a \"normal\" struct. Strings are represented as offsets that\npoint to memory past the end of the struct. We'd need an extra AM hook\nthat allocateReloptStruct can call into.\n\n* We could refactor the validation logic so that extra options don't\ncount immediately as an error, but we instead save them in a different\narray, and pass them to an AM-specific validation routine. But we have\nno place to really put these options once they are parsed, because rel-\n>rd_options is already holding the StdRdOptions struct, and there's no\nseparate place in the catalog for AM-specific reloptions. So the\nextension would then need to re-parse them, and stash them in\nrd_amcache or something.\n\n* We could introduce a new AM routine that returns a custom\nrelopt_kind, created with add_reloption_kind(). Then, we could change\nheap_reloptions to call default_reloptions like:\n\n return default_reloptions(reloptions, validate,\n RELOPT_KIND_HEAP|customReloptKind);\n\nThis still requires my patch, because we need to avoid the second\nvalidation step. It also requires some extra code for TOAST tables,\nbecause they can also be a custom table access method. The benefit over\nmy current patch is that extensions wouldn't be creating new options\nfor RELOPT_KIND_HEAP, they would create them only for their own custom\nrelopt kind, so if you try to use those options with a heap, you would\nget an error.\n\n\nSuggestions welcome.\n\nRegards,\n\tJeff Davis\n\n\n\n\n", "msg_date": "Tue, 01 Sep 2020 10:21:26 -0700", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": true, "msg_subject": "Re: Reloptions for table access methods" }, { "msg_contents": "\n\n\n\n\n‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn Tuesday, 1 September 2020 20:21, Jeff Davis <pgsql@j-davis.com> wrote:\n\n\n>\n> I'm fine removing the \"validate\" parameter completely for the sake of\n> consistency.\n\nFWIW, the more I think about this, I would agree with the removal.\nHowever, isn't this mechanism used for other things too, e.g. attribute_reloptions,\ntablespace_reloptions, that rely on the validation at that layer?. If my understanding\nis correct, then simply removing the parameter would not cut it and a more extensive\nrefactoring would be needed.\n\n>\n> > [snip]\n>\n> The problem case would be a situation like the following:\n>\n> 1. Someone loads an extension that creates a new reloption\n> \"custom_reloption\" of kind RELOPT_KIND_HEAP for their table access\n> method \"my_tableam\".\n>\n> 2. They then create a table and forget to specify \"USING my_tableam\",\n> but use the option \"custom_reloption=123\".\n>\n> Ideally, that would throw an error because \"custom_reloption\" is only\n> valid for \"my_tableam\"; but with my patch, no error would be thrown\n> because the extension has already added the reloption. It would just\n> create a normal heap and \"custom_reloption=123\" would be ignored.\n\nThis is something that I struggle to understand as an \"error\". In the example,\nthe set RELOPT_KIND_HEAP was extended for everyone. Regardless of whether\nthe newly added member will be used or not.\n\nI mean, if the intention was to add reloptions specific to the extension,\nshouldn't a new RELOPT_KIND_XXX be introduced? You seem to be thinking\nalong the same lines. Please, correct me if I understand you wrong.\n\nWhat I am trying to say, is that with the current patch, I feel the behaviour\nis not strange nor unexpected.\n\n\n> I went with the simple approach because fixing that problem seemed a\n> bit over-engineered.\n\nFixing that problem seems worth it on the long run. I do see the benefit of\nthe simple approach on the meantime.\n\n//Georgios\n\n>\n> Regards,\n> Jeff Davis\n>\n\n\n\n\n", "msg_date": "Thu, 03 Sep 2020 12:54:00 +0000", "msg_from": "gkokolatos@pm.me", "msg_from_op": false, "msg_subject": "Re: Reloptions for table access methods" }, { "msg_contents": "On Tue, 1 Sept 2020 at 18:21, Jeff Davis <pgsql@j-davis.com> wrote:\n\n> I went with the simple approach because fixing that problem seemed a\n> bit over-engineered. Here are some thoughts on what we could do:\n\nThe simple patch is admirable, but not something we should put into core.\n\nI definitely don't agree with the premise that all existing heap\noptions should be common across all new or extension tableAMs. There\nare dozens of such options and I don't believe that they would all\nhave meaning in all future storage plugins.\n\nI think options should just work exactly the same for Indexes and Tables.\n\n-- \nSimon Riggs http://www.EnterpriseDB.com/\n\n\n", "msg_date": "Tue, 15 Dec 2020 17:37:32 +0000", "msg_from": "Simon Riggs <simon@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Reloptions for table access methods" }, { "msg_contents": "On Tue, 2020-12-15 at 17:37 +0000, Simon Riggs wrote:\n> \n> I definitely don't agree with the premise that all existing heap\n> options should be common across all new or extension tableAMs. There\n> are dozens of such options and I don't believe that they would all\n> have meaning in all future storage plugins.\n\nI agree in principle, but looking at the options that are present\ntoday, a lot of them are integrated into general database features,\nlike autovacuum, toast, logical replication, and parellel query\nplanning. \n\nWe need to have some answer about how these features should interact\nwith a custom AM if we can't assume anything about the reloptions it\nunderstands.\n\n> I think options should just work exactly the same for Indexes and\n> Tables.\n\nHow should that work with the existing code? Should we have separate AM\nhooks for each of these interaction points, and then have the AM figure\nout how to handle its options? What about the toast.* options?\n\nIt feels like some common options would make sense to avoid too much\ncode duplication.\n\nI am not trying to push this in a specific direction, but I don't have\na lot of good answers, so I went for the simplest thing I could think\nof that would allow an extension to have its own options, even if it's\na bit hacky. I'm open to alternatives.\n\nRegards,\n\tJeff Davis\n\n\n\n\n", "msg_date": "Tue, 15 Dec 2020 15:59:02 -0800", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": true, "msg_subject": "Re: Reloptions for table access methods" }, { "msg_contents": "On Tue, Dec 15, 2020 at 03:59:02PM -0800, Jeff Davis wrote:\n> How should that work with the existing code? Should we have separate AM\n> hooks for each of these interaction points, and then have the AM figure\n> out how to handle its options? What about the toast.* options?\n\nIt seems to me that we would want a callback for options that is part\nof TableAmRoutine to do the loading work, no? The bigger picture is\nmore complex than that though because all in-core AMs rely on\nbuild_reloptions() to do the work which itself depends on a et of\npre-existing reloptions (all the static relOpts array). In the end,\nI'd like to think that we should remove the dependency between relopt\nbuild and initialization state, then switch all the different AMs to\ndo something similar to create_reloptions_table() in dummy_index_am.c\nto define a new set of reloptions, except that we'd want to preload\nall the options at backend startup or something similar to that for\nall in-core AMs, for tables and indexes.\n\n> It feels like some common options would make sense to avoid too much\n> code duplication.\n\nHaving a set of options that can be plugged in to any AMs, like a set\nof preset options for autovacuum or toast makes sense to have.\n\n> I am not trying to push this in a specific direction, but I don't have\n> a lot of good answers, so I went for the simplest thing I could think\n> of that would allow an extension to have its own options, even if it's\n> a bit hacky. I'm open to alternatives.\n\nFWIW, I agree with Simon's feeling that bypassing a sanity check does\nnot feel like a good solution in the long term.\n--\nMichael", "msg_date": "Wed, 16 Dec 2020 09:55:27 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Reloptions for table access methods" }, { "msg_contents": "On Tue, 15 Dec 2020 at 23:59, Jeff Davis <pgsql@j-davis.com> wrote:\n>\n> On Tue, 2020-12-15 at 17:37 +0000, Simon Riggs wrote:\n> >\n> > I definitely don't agree with the premise that all existing heap\n> > options should be common across all new or extension tableAMs. There\n> > are dozens of such options and I don't believe that they would all\n> > have meaning in all future storage plugins.\n>\n> I agree in principle, but looking at the options that are present\n> today, a lot of them are integrated into general database features,\n> like autovacuum, toast, logical replication, and parellel query\n> planning.\n>\n> We need to have some answer about how these features should interact\n> with a custom AM if we can't assume anything about the reloptions it\n> understands.\n>\n> > I think options should just work exactly the same for Indexes and\n> > Tables.\n>\n> How should that work with the existing code? Should we have separate AM\n> hooks for each of these interaction points, and then have the AM figure\n> out how to handle its options? What about the toast.* options?\n>\n> It feels like some common options would make sense to avoid too much\n> code duplication.\n>\n> I am not trying to push this in a specific direction, but I don't have\n> a lot of good answers, so I went for the simplest thing I could think\n> of that would allow an extension to have its own options, even if it's\n> a bit hacky. I'm open to alternatives.\n\nYour argument seems to be that all new Table AMs should offer some\nkind of support for these \"standard\" options, even if it is to accept\nand then ignore them, which would presumably require them to document\nthat. If that is the case, then at very least offer a doc patch that\nsays that so people know what to do and doc comments describe how we\nshould treat new parameters in the future.\n\nBut you cannot seriously argue that a one line patch that changes user\nvisible behavior can be acceptable in Postgres core without tests or\ndocs or code comments. You know as a Committer that that position is\nnot sustainable.\n\nMinor changes could be OK if they are complete. Please either push\nforward to a usable commit or withdraw, so other options can be\nconsidered.\n\n-- \nSimon Riggs http://www.EnterpriseDB.com/\n\n\n", "msg_date": "Wed, 30 Dec 2020 21:23:19 +0000", "msg_from": "Simon Riggs <simon@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Reloptions for table access methods" }, { "msg_contents": "On Wed, 2020-12-30 at 21:23 +0000, Simon Riggs wrote:\n> But you cannot seriously argue that a one line patch that changes\n> user\n> visible behavior can be acceptable in Postgres core without tests or\n> docs or code comments.\n\nHi Simon,\n\nOften, good documented APIs come about after a few extensions gain\nexperience hacking things together using undocumented assumptions and\ninternal APIs. But in this case, extension authors have no opportunity\nto hack in reloptions for a TableAM, because of this needless extra\ncheck that my patch would eliminate.\n\nThe patch does not have any user-visible impact. To have any effect, an\nextension would need to use these internal APIs in a specific way that\nis not documented externally. I see my tiny patch as a tiny improvement\nto the backend code because it eliminates a useless extra check, and\ntherefore doesn't need much justification. If others see it as a burden\non the engine code, that's a different story.\n\nIf we insist that this must be a fully-supported feature or nothing at\nall, then I'll withdraw the patch. But I doubt that will result in a\nproper feature for v14, it just means that when we do get around to\nsupporting extensible reloptions, there will be no hacks in the wild to\nlearn from.\n\nRegards,\n\tJeff Davis\n\n\n\n\n", "msg_date": "Sat, 02 Jan 2021 10:44:20 -0800", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": true, "msg_subject": "Re: Reloptions for table access methods" }, { "msg_contents": "On Sat, Jan 2, 2021 at 6:44 PM Jeff Davis <pgsql@j-davis.com> wrote:\n>\n> On Wed, 2020-12-30 at 21:23 +0000, Simon Riggs wrote:\n> > But you cannot seriously argue that a one line patch that changes\n> > user\n> > visible behavior can be acceptable in Postgres core without tests or\n> > docs or code comments.\n>\n> Hi Simon,\n>\n> Often, good documented APIs come about after a few extensions gain\n> experience hacking things together using undocumented assumptions and\n> internal APIs. But in this case, extension authors have no opportunity\n> to hack in reloptions for a TableAM, because of this needless extra\n> check that my patch would eliminate.\n>\n> The patch does not have any user-visible impact. To have any effect, an\n> extension would need to use these internal APIs in a specific way that\n> is not documented externally. I see my tiny patch as a tiny improvement\n> to the backend code because it eliminates a useless extra check, and\n> therefore doesn't need much justification. If others see it as a burden\n> on the engine code, that's a different story.\n>\n> If we insist that this must be a fully-supported feature or nothing at\n> all, then I'll withdraw the patch. But I doubt that will result in a\n> proper feature for v14, it just means that when we do get around to\n> supporting extensible reloptions, there will be no hacks in the wild to\n> learn from.\n\nThanks for the reply. I'm trying to get my head around this before a\nlonger reply.\n\n-- \nSimon Riggs http://www.EnterpriseDB.com/\n\n\n", "msg_date": "Thu, 7 Jan 2021 19:32:17 +0000", "msg_from": "Simon Riggs <simon.riggs@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Reloptions for table access methods" }, { "msg_contents": "On 1/7/21 2:32 PM, Simon Riggs wrote:\n> On Sat, Jan 2, 2021 at 6:44 PM Jeff Davis <pgsql@j-davis.com> wrote:\n>>\n>> On Wed, 2020-12-30 at 21:23 +0000, Simon Riggs wrote:\n>>> But you cannot seriously argue that a one line patch that changes\n>>> user\n>>> visible behavior can be acceptable in Postgres core without tests or\n>>> docs or code comments.\n>>\n>> Often, good documented APIs come about after a few extensions gain\n>> experience hacking things together using undocumented assumptions and\n>> internal APIs. But in this case, extension authors have no opportunity\n>> to hack in reloptions for a TableAM, because of this needless extra\n>> check that my patch would eliminate.\n>>\n>> The patch does not have any user-visible impact. To have any effect, an\n>> extension would need to use these internal APIs in a specific way that\n>> is not documented externally. I see my tiny patch as a tiny improvement\n>> to the backend code because it eliminates a useless extra check, and\n>> therefore doesn't need much justification. If others see it as a burden\n>> on the engine code, that's a different story.\n>>\n>> If we insist that this must be a fully-supported feature or nothing at\n>> all, then I'll withdraw the patch. But I doubt that will result in a\n>> proper feature for v14, it just means that when we do get around to\n>> supporting extensible reloptions, there will be no hacks in the wild to\n>> learn from.\n> \n> Thanks for the reply. I'm trying to get my head around this before a\n> longer reply.\n\nSimon, have you had time to formulate your thoughts on this patch?\n\nRegards,\n-- \n-David\ndavid@pgmasters.net\n\n\n", "msg_date": "Thu, 18 Mar 2021 10:37:40 -0400", "msg_from": "David Steele <david@pgmasters.net>", "msg_from_op": false, "msg_subject": "Re: Reloptions for table access methods" } ]
[ { "msg_contents": "Hi,\n\nas a continuation of [1], I've split-off the zero page header case from\nthe last patch, as this one seems less contentious.\n\n\nMichael\n\n[1] https://commitfest.postgresql.org/28/2308/\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", "msg_date": "Tue, 01 Sep 2020 12:22:29 +0200", "msg_from": "Michael Banck <michael.banck@credativ.de>", "msg_from_op": true, "msg_subject": "[patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "On 01.09.2020 13:22, Michael Banck wrote:\n> Hi,\n>\n> as a continuation of [1], I've split-off the zero page header case from\n> the last patch, as this one seems less contentious.\n>\n>\n> Michael\n>\n> [1] https://commitfest.postgresql.org/28/2308/\n>\nI've looked through the previous discussion. As far as I got it, most of \nthe controversy was about online checksums improvements.\n\nThe warning about pd_upper inconsistency that you've added is a good \naddition. The patch is a bit messy, though, because a huge code block \nwas shifted.\n\nWill it be different, if you just leave\n     \"if (!PageIsNew(page) && PageGetLSN(page) < startptr)\"\nblock as it was, and add\n     \"else if (PageIsNew(page) && !PageIsZero(page))\" ?\n\n\nWhile on it, I also have a few questions about the code around:\n\n1) Maybe we can use other header sanity checks from PageIsVerified() as \nwell? Or even the function itself.\n\n2) > /* Reset loop to validate the block again */\nHow many times do we try to reread the block? Is one reread enough?\nSpeaking of which, 'reread_cnt' name looks confusing to me. I would \nexpect that this variable contains a number of attempts, not the number \nof bytes read.\n\nIf everyone agrees, that for basebackup purpose it's enough to rely on a \nsingle reread, I'm ok with it.\nAnother approach is to read the page directly from shared buffers to \nensure that the page is fine. This way is more complicated, but should \nbe almost bullet-proof. Using it we can also check pages with lsn >= \nstartptr.\n\n3) Judging by warning messages, we count checksum failures per file, not \nper page, and don't report after a fifth failure. Why so?  Is it a \ncommon case that so many pages of one file are corrupted?\n\n-- \nAnastasia Lubennikova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Wed, 2 Sep 2020 16:50:14 +0300", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "On Wed, Sep 02, 2020 at 04:50:14PM +0300, Anastasia Lubennikova wrote:\n> I've looked through the previous discussion. As far as I got it, most of the\n> controversy was about online checksums improvements.\n\nThis patch is waiting on author for two weeks now. Michael, could you\nreply to the points raised by Anastasia?\n--\nMichael", "msg_date": "Thu, 17 Sep 2020 13:33:29 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "Hi,\n\nAm Mittwoch, den 02.09.2020, 16:50 +0300 schrieb Anastasia Lubennikova:\n> On 01.09.2020 13:22, Michael Banck wrote:\n> > as a continuation of [1], I've split-off the zero page header case from\n> > the last patch, as this one seems less contentious.\n> > [1] https://commitfest.postgresql.org/28/2308/\n> \n> I've looked through the previous discussion. As far as I got it, most of \n> the controversy was about online checksums improvements.\n> \n> The warning about pd_upper inconsistency that you've added is a good \n> addition. The patch is a bit messy, though, because a huge code block \n> was shifted.\n> \n> Will it be different, if you just leave\n> \"if (!PageIsNew(page) && PageGetLSN(page) < startptr)\"\n> block as it was, and add\n> \"else if (PageIsNew(page) && !PageIsZero(page))\" ?\n\nThanks, that does indeed look better as a patch and I think it's fine\nas-is for the code as well, I've attached a v2.\n\n> While on it, I also have a few questions about the code around:\n\nAll fair points, but I think those should be handled in another patch,\nif any.\n\n> 1) Maybe we can use other header sanity checks from PageIsVerified() as \n> well? Or even the function itself.\n\nYeah, I'll keep that in mind.\n\n> 2) > /* Reset loop to validate the block again */\n> How many times do we try to reread the block? Is one reread enough?\n\nNot sure whether more rereads would help, but I think the general\ndirection was to replace this with something better anyway I think (see\nbelow).\n\n> Speaking of which, 'reread_cnt' name looks confusing to me. I would \n> expect that this variable contains a number of attempts, not the number \n> of bytes read.\n\nWell, there are other \"cnt\" variables that keep the number of bytes read\nin that file, so it does not seem to be out of place for me. A comment\nmight not hurt though.\n\nOn second glance, it should maybe also be of size_t and not int type, as\nis the other cnt variable?\n\n> If everyone agrees, that for basebackup purpose it's enough to rely on a \n> single reread, I'm ok with it.\n> Another approach is to read the page directly from shared buffers to \n> ensure that the page is fine. This way is more complicated, but should \n> be almost bullet-proof. Using it we can also check pages with lsn >= \n> startptr.\n\nRight, that's what Andres also advocated for initially I think, and what\nshould be done going forward.\n\n> 3) Judging by warning messages, we count checksum failures per file, not \n> per page, and don't report after a fifth failure. Why so? Is it a \n> common case that so many pages of one file are corrupted?\n\nI think this was a request during the original review, on the basis that\nif we have more than a few checksum errors, it's likely there is\nsomething fundamentally broken and it does not make sense to spam the\nlog with potentially millions of broken checksums.\n\n\nCheers,\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", "msg_date": "Tue, 22 Sep 2020 16:26:31 +0200", "msg_from": "Michael Banck <michael.banck@credativ.de>", "msg_from_op": true, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "Hi,\n\nAm Dienstag, den 22.09.2020, 16:26 +0200 schrieb Michael Banck:\n> Am Mittwoch, den 02.09.2020, 16:50 +0300 schrieb Anastasia Lubennikova:\n> > I've looked through the previous discussion. As far as I got it, most of \n> > the controversy was about online checksums improvements.\n> > \n> > The warning about pd_upper inconsistency that you've added is a good \n> > addition. The patch is a bit messy, though, because a huge code block \n> > was shifted.\n> > \n> > Will it be different, if you just leave\n> > \"if (!PageIsNew(page) && PageGetLSN(page) < startptr)\"\n> > block as it was, and add\n> > \"else if (PageIsNew(page) && !PageIsZero(page))\" ?\n> \n> Thanks, that does indeed look better as a patch and I think it's fine\n> as-is for the code as well, I've attached a v2.\n\nSorry, forgot to add you as reviewer in the proposed commit message,\nI've fixed that up now in V3.\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", "msg_date": "Tue, 22 Sep 2020 16:30:19 +0200", "msg_from": "Michael Banck <michael.banck@credativ.de>", "msg_from_op": true, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "\nOn 22.09.2020 17:30, Michael Banck wrote:\n> Hi,\n>\n> Am Dienstag, den 22.09.2020, 16:26 +0200 schrieb Michael Banck:\n>> Am Mittwoch, den 02.09.2020, 16:50 +0300 schrieb Anastasia Lubennikova:\n>>> I've looked through the previous discussion. As far as I got it, most of\n>>> the controversy was about online checksums improvements.\n>>>\n>>> The warning about pd_upper inconsistency that you've added is a good\n>>> addition. The patch is a bit messy, though, because a huge code block\n>>> was shifted.\n>>>\n>>> Will it be different, if you just leave\n>>> \"if (!PageIsNew(page) && PageGetLSN(page) < startptr)\"\n>>> block as it was, and add\n>>> \"else if (PageIsNew(page) && !PageIsZero(page))\" ?\n>> Thanks, that does indeed look better as a patch and I think it's fine\n>> as-is for the code as well, I've attached a v2.\n> Sorry, forgot to add you as reviewer in the proposed commit message,\n> I've fixed that up now in V3.\n>\n>\n> Michael\n>\nGreat. This version looks good to me.\nThank you for answering my questions, I agree, that we can work on them \nin separate threads.\n\nSo I mark this one as ReadyForCommitter.\n\nThe only minor problem is a typo (?) in the proposed commit message.\n\"If a page is all zero, consider that a checksum failure.\" It should be \n\"If a page is NOT all zero...\".\n\n-- \nAnastasia Lubennikova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Thu, 24 Sep 2020 17:24:27 +0300", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "Hi,\n\nAm Donnerstag, den 24.09.2020, 17:24 +0300 schrieb Anastasia\nLubennikova:\n> So I mark this one as ReadyForCommitter.\n\nThanks!\n\n> The only minor problem is a typo (?) in the proposed commit message.\n> \"If a page is all zero, consider that a checksum failure.\" It should be \n> \"If a page is NOT all zero...\".\n\nOh right, I've fixed up the commit message in the attached V4.\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", "msg_date": "Fri, 25 Sep 2020 08:53:27 +0200", "msg_from": "Michael Banck <michael.banck@credativ.de>", "msg_from_op": true, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "On Fri, Sep 25, 2020 at 08:53:27AM +0200, Michael Banck wrote:\n> Oh right, I've fixed up the commit message in the attached V4.\n\nNot much a fan of what's proposed here, for a couple of reasons:\n- If the page is not new, we should check if the header is sane or\nnot.\n- It may be better to actually count checksum failures if these are\nrepeatable in a given block, and report them.\n- The code would be more simple with a \"continue\" added for a block\ndetected as new or with a LSN newer than the backup start.\n- The new error messages are confusing, and I think that these are\nhard to translate in a meaningful way.\n\nSo I think that we should try to use PageIsVerified() directly in the\ncode path of basebackup.c, and this requires a couple of changes to\nmake the routine more extensible:\n- Addition of a dboid argument for pgstat_report_checksum_failure(),\nwhose call needs to be changed to use the *_in_db() flavor.\n- Addition of an option to decide if a log should be generated or\nnot.\n- Addition of an option to control if a checksum failure should be\nreported to pgstat or not, even if this is actually linked to the\nprevious point, I have seen cases where being able to control both\nseparately would be helpful, particularly the log part.\n\nFor the last two ones, I would use an extensible argument based on\nbits32 with a set of flags that the caller can set at will. Something\nelse I would recommend here is to use an error context for the case\nwhere we want to log a retry number in the base backup loop that\naccepts false positives, with the blkno and the physical file name\nwhen we find failures after retries.\n--\nMichael", "msg_date": "Wed, 7 Oct 2020 17:18:52 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "On 07.10.2020 11:18, Michael Paquier wrote:\n> On Fri, Sep 25, 2020 at 08:53:27AM +0200, Michael Banck wrote:\n>> Oh right, I've fixed up the commit message in the attached V4.\n> Not much a fan of what's proposed here, for a couple of reasons:\n> - If the page is not new, we should check if the header is sane or\n> not.\n> - It may be better to actually count checksum failures if these are\n> repeatable in a given block, and report them.\n> - The code would be more simple with a \"continue\" added for a block\n> detected as new or with a LSN newer than the backup start.\n> - The new error messages are confusing, and I think that these are\n> hard to translate in a meaningful way.\nI am interested in moving this patch forward, so here is the updated v5.\nThis version uses PageIsVerified. All error messages are left unchanged.\n> So I think that we should try to use PageIsVerified() directly in the\n> code path of basebackup.c, and this requires a couple of changes to\n> make the routine more extensible:\n> - Addition of a dboid argument for pgstat_report_checksum_failure(),\n> whose call needs to be changed to use the *_in_db() flavor.\n\nIn the current patch, PageIsVerifed called from pgbasebackup simply \ndoesn't report failures to pgstat.\nBecause in basebackup.c we already report checksum failures separately. \nOnce per file.\n ��� ��� pgstat_report_checksum_failures_in_db(dboid, checksum_failures);\n\nShould we change this too? I don't see any difference.\n\n> - Addition of an option to decide if a log should be generated or\n> not.\n> - Addition of an option to control if a checksum failure should be\n> reported to pgstat or not, even if this is actually linked to the\n> previous point, I have seen cases where being able to control both\n> separately would be helpful, particularly the log part.\n>\n> For the last two ones, I would use an extensible argument based on\n> bits32 with a set of flags that the caller can set at will.\nDone.\n\n-- \nAnastasia Lubennikova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 16 Oct 2020 18:02:52 +0300", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "On Fri, Oct 16, 2020 at 06:02:52PM +0300, Anastasia Lubennikova wrote:\n> In the current patch, PageIsVerifed called from pgbasebackup simply doesn't\n> Should we change this too? I don't see any difference.\n\nI considered that, but now that does not seem worth bothering here.\n\n> Done.\n\nThanks for the updated patch. I have played with dd and some fake\nfiles to check the validity of the zero-case (as long as pd_lsn does\nnot go wild). Here are some comments, with an updated patch attached:\n- Added a PageIsVerifiedExtended to make this patch back-patchable,\nwith the original routine keeping its original shape.\n- I did not like much to show the WARNING from PageIsVerified() for\nthe report, and we'd lose some context related to the base backups.\nThe important part is to know which blocks from which files are found\nas problematic.\n- Switched the checks to have PageIsVerified() placed first in the\nhierarchy, so as we do all the basic validity checks before a look at\nthe LSN. This is not really change things logically.\n- The meaning of block_retry is also the opposite of what it should be\nin the original code? IMO, the flag should be set to true if we still\nare fine to retry a block, and set it to false once the one-time retry\nhas failed.\n- Moved the hardcoded failure report threshold of 5 into its own\nvariable.\n- The error strings are not really consistent with the project style\nin this area. These are usually not spawned across multiple lines to\nease searches with grep or such.\n\nAnastasia, Michael B, does that look OK to you?\n\nNB: This patch fixes only one problem, the zero-page case, as it was\nthe intention of Michael B to split this part into its own thread. We\nstill have, of course, a second problem when it comes to a random LSN\nput into the page header which could mask an actual checksum failure\nso this only takes care of half the issues. Having a correct LSN\napproximation is a tricky problem IMO, but we could improve things by\nhaving some delta with an extra WAL page on top of GetInsertRecPtr().\nAnd this function cannot be used for base backups taken from\nstandbys.\n--\nMichael", "msg_date": "Tue, 20 Oct 2020 15:24:32 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "On 20.10.2020 09:24, Michael Paquier wrote:\n> On Fri, Oct 16, 2020 at 06:02:52PM +0300, Anastasia Lubennikova wrote:\n>> In the current patch, PageIsVerifed called from pgbasebackup simply doesn't\n>> Should we change this too? I don't see any difference.\n> I considered that, but now that does not seem worth bothering here.\n>\n>> Done.\n> Thanks for the updated patch. I have played with dd and some fake\n> files to check the validity of the zero-case (as long as pd_lsn does\n> not go wild). Here are some comments, with an updated patch attached:\n> - Added a PageIsVerifiedExtended to make this patch back-patchable,\n> with the original routine keeping its original shape.\nThank you. I always forget about this. Do we have any checklist for such \nchanges, that patch authors and reviewers can use?\n> - I did not like much to show the WARNING from PageIsVerified() for\n> the report, and we'd lose some context related to the base backups.\n> The important part is to know which blocks from which files are found\n> as problematic.\n> - Switched the checks to have PageIsVerified() placed first in the\n> hierarchy, so as we do all the basic validity checks before a look at\n> the LSN. This is not really change things logically.\n> - The meaning of block_retry is also the opposite of what it should be\n> in the original code? IMO, the flag should be set to true if we still\n> are fine to retry a block, and set it to false once the one-time retry\n> has failed.\n\nAgree.\n\n> - The error strings are not really consistent with the project style\n> in this area. These are usually not spawned across multiple lines to\n> ease searches with grep or such.\nSame question as above. I don't see this info about formatting in the \nerror message style guide in documentation. Is it mentioned somewhere else?\n> Anastasia, Michael B, does that look OK to you?\nThe final patch looks good to me.\n> NB: This patch fixes only one problem, the zero-page case, as it was\n> the intention of Michael B to split this part into its own thread. We\n> still have, of course, a second problem when it comes to a random LSN\n> put into the page header which could mask an actual checksum failure\n> so this only takes care of half the issues. Having a correct LSN\n> approximation is a tricky problem IMO, but we could improve things by\n> having some delta with an extra WAL page on top of GetInsertRecPtr().\n> And this function cannot be used for base backups taken from\n> standbys.\n\nWe can also read such pages via shared buffers to be 100% sure.\n\n-- \nAnastasia Lubennikova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Thu, 22 Oct 2020 00:47:03 +0300", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "On Thu, Oct 22, 2020 at 12:47:03AM +0300, Anastasia Lubennikova wrote:\n> Thank you. I always forget about this. Do we have any checklist for such\n> changes, that patch authors and reviewers can use?\n\nNot really. That's more a habit than anything else where any\nnon-static routine that we publish could be used by some out-of-core \ncode, so maintaining a pure API compatibility on stable branches is\nessential.\n\n> We can also read such pages via shared buffers to be 100% sure.\n\nYeah, but this has its limits as well. One can use\nignore_checksum_failure, but this can actually be very dangerous as\nyou can finish by loading into shared buffers a page that has a header\nthought as sane but with a large portion of its page randomly\ncorrupted, spreading corruption around and leading to more fancy\nlogic failures in Postgres, with more panic from customers. Not using\nignore_checksum_failure is safer, but it makes an analyze of the\ndamages for a given file harder as things would stop at the first\nfailure of a file with a seqscan. pg_prewarm can help here, but\nthat's not the goal of the tool to do that either.\n\nWe definitely need a different approach that guarantees that a page is\ncorrectly locked with no concurrent I/O while checked on retry, and I\nam looking at that for the SQL-level check. That's not something I\nwould do in v13 though, but we can make the existing logic much more\nreliable with a set of fixed retries and some sleeps in-between. A\nmaximum of 5 retries with 100ms seems like a good balance seen from\nhere, but that's not a perfect science of course depending on the\nhardware latency.\n\nThis has been a sensitive topic during the stability period of v13\nwith many committers commenting on the issue, so I'd rather be very\ncareful that there are no objections to what's published here, and in\nconsequence I am going to ping the other thread on the matter. For\nnow I have the attached to address the zero-case and the random LSN\ncase.\n--\nMichael", "msg_date": "Thu, 22 Oct 2020 10:25:19 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "On Thu, Oct 22, 2020 at 9:25 AM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> On Thu, Oct 22, 2020 at 12:47:03AM +0300, Anastasia Lubennikova wrote:\n> > Thank you. I always forget about this. Do we have any checklist for such\n> > changes, that patch authors and reviewers can use?\n>\n> Not really. That's more a habit than anything else where any\n> non-static routine that we publish could be used by some out-of-core\n> code, so maintaining a pure API compatibility on stable branches is\n> essential.\n>\n> > We can also read such pages via shared buffers to be 100% sure.\n>\n> Yeah, but this has its limits as well. One can use\n> ignore_checksum_failure, but this can actually be very dangerous as\n> you can finish by loading into shared buffers a page that has a header\n> thought as sane but with a large portion of its page randomly\n> corrupted, spreading corruption around and leading to more fancy\n> logic failures in Postgres, with more panic from customers. Not using\n> ignore_checksum_failure is safer, but it makes an analyze of the\n> damages for a given file harder as things would stop at the first\n> failure of a file with a seqscan. pg_prewarm can help here, but\n> that's not the goal of the tool to do that either.\n>\n> We definitely need a different approach that guarantees that a page is\n> correctly locked with no concurrent I/O while checked on retry, and I\n> am looking at that for the SQL-level check. That's not something I\n> would do in v13 though, but we can make the existing logic much more\n> reliable with a set of fixed retries and some sleeps in-between. A\n> maximum of 5 retries with 100ms seems like a good balance seen from\n> here, but that's not a perfect science of course depending on the\n> hardware latency.\n>\n> This has been a sensitive topic during the stability period of v13\n> with many committers commenting on the issue, so I'd rather be very\n> careful that there are no objections to what's published here, and in\n> consequence I am going to ping the other thread on the matter. For\n> now I have the attached to address the zero-case and the random LSN\n> case.\n\nI'm a bit worried about this approach, as if I understand correctly\nthis can lead to false positive reports. I've certainly seen systems\nwith IO stalled for more than 500ms, so while this is not frequent\nthis could still happen.\n\nAbout the patch:\n\n+ * doing this check, causing a false positive. If that\n+ * happens, a page is retried once, with an error reported if\n+ * the second attempt also fails.\n\n[...]\n\n+ /* The verification of a page has failed, retry once */\n+ if (block_attempts < PAGE_RETRY_THRESHOLD)\n+ {\n\nBoth those comments seem to refer to the previous \"retry only once\"\napproach. Apart from that and my concerns on the new heuristics, the\npatch looks good, +1 for PageIsVerifiedExtended()!\n\n\n", "msg_date": "Thu, 22 Oct 2020 14:27:34 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "On Thu, Oct 22, 2020 at 02:27:34PM +0800, Julien Rouhaud wrote:\n> I'm a bit worried about this approach, as if I understand correctly\n> this can lead to false positive reports. I've certainly seen systems\n> with IO stalled for more than 500ms, so while this is not frequent\n> this could still happen.\n\nThe possibility of false positives is not a new thing with this\nfeature as currently shaped. On HEAD, this code actually just does\none retry, without waiting at all for the operation potentially\nhappening in parallel to finish, so that's actually worse. And that's\nassuming that the pd_lsn of the page did not get touched by a\ncorruption as we would simply miss a broken page. So, with a\nnon-locking approach, we limit ourselves to tweaking the number of\nretries and some sleeps :(\n\nI am not sure that increasing the sleep of 100ms is a good thing on\nnot-so-slow disks, but we could increase the number of retries. The\npatch makes that easier to change at least. FWIW, I don't like that\nthis code, with a real risk of false positives, got merged to begin\nwith, and I think that other people share the same opinion, but it is\nnot like we can just remove it on a branch already released either..\nAnd I am not sure if we have done such things in the past for stable\nbranches. If we were to do that, we could just make the operation a\nno-op, and keep some traces of the grammar for compatibility.\n\n> About the patch:\n> \n> + * doing this check, causing a false positive. If that\n> + * happens, a page is retried once, with an error reported if\n> + * the second attempt also fails.\n> \n> [...]\n> \n> + /* The verification of a page has failed, retry once */\n> + if (block_attempts < PAGE_RETRY_THRESHOLD)\n> + {\n\nOops. Thanks, I got that changed on my branch.\n--\nMichael", "msg_date": "Thu, 22 Oct 2020 15:52:01 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "On 22.10.2020 04:25, Michael Paquier wrote:\n> On Thu, Oct 22, 2020 at 12:47:03AM +0300, Anastasia Lubennikova wrote:\n>> We can also read such pages via shared buffers to be 100% sure.\n> Yeah, but this has its limits as well. One can use\n> ignore_checksum_failure, but this can actually be very dangerous as\n> you can finish by loading into shared buffers a page that has a header\n> thought as sane but with a large portion of its page randomly\n> corrupted, spreading corruption around and leading to more fancy\n> logic failures in Postgres, with more panic from customers. Not using\n> ignore_checksum_failure is safer, but it makes an analyze of the\n> damages for a given file harder as things would stop at the first\n> failure of a file with a seqscan. pg_prewarm can help here, but\n> that's not the goal of the tool to do that either.\nI was thinking about applying this only to pages with LSN > startLSN.\n\nMost of such pages are valid and already in memory, because they were \nchanged just recently, so no need for pg_prewarm here. If such LSN \nappeared because of a data corruption, page verification from inside \nReadBuffer() will report an error first. In proposed function, we can \nhandle this error in any fashion we want. Something like:\n\nif (PageGetLSN(page) > startptr)\n{\n ��� if (!read_page_via_buffercache())\n\n ��� ��� //throw a warning about corrupted page\n ��� ��� //handle checksum error as needed\n ��� else\n ��� ��� //page is valid. No worries\n}\n\n-- \nAnastasia Lubennikova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Thu, 22 Oct 2020 15:11:45 +0300", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "On Thu, Oct 22, 2020 at 03:11:45PM +0300, Anastasia Lubennikova wrote:\n> Most of such pages are valid and already in memory, because they were\n> changed just recently, so no need for pg_prewarm here. If such LSN appeared\n> because of a data corruption, page verification from inside ReadBuffer()\n> will report an error first. In proposed function, we can handle this error\n> in any fashion we want. Something like:\n> \n> if (PageGetLSN(page) > startptr)\n> {\n>     if (!read_page_via_buffercache())\n> \n>         //throw a warning about corrupted page\n>         //handle checksum error as needed\n>     else\n>         //page is valid. No worries\n> }\n\nYeah, we could try to make the logic a bit more complicated like\nthat. However, for any code path relying on a page read without any\nlocking insurance, we cannot really have a lot of trust in any of the\nfields assigned to the page as this could just be random corruption\ngarbage, and the only thing I am ready to trust here a checksum\nmismatch check, because that's the only field on the page that's\nlinked to its full contents on the 8k page. This also keeps the code\nsimpler.\n--\nMichael", "msg_date": "Fri, 23 Oct 2020 08:00:08 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "On Fri, Oct 23, 2020 at 08:00:08AM +0900, Michael Paquier wrote:\n> Yeah, we could try to make the logic a bit more complicated like\n> that. However, for any code path relying on a page read without any\n> locking insurance, we cannot really have a lot of trust in any of the\n> fields assigned to the page as this could just be random corruption\n> garbage, and the only thing I am ready to trust here a checksum\n> mismatch check, because that's the only field on the page that's\n> linked to its full contents on the 8k page. This also keeps the code\n> simpler.\n\nA small update here. I have extracted the refactored part for\nPageIsVerified() and committed it as that's independently useful.\nThis makes the patch proposed here simpler on HEAD, leading to the\nattached.\n--\nMichael", "msg_date": "Mon, 26 Oct 2020 10:13:15 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "On 26.10.2020 04:13, Michael Paquier wrote:\n> On Fri, Oct 23, 2020 at 08:00:08AM +0900, Michael Paquier wrote:\n>> Yeah, we could try to make the logic a bit more complicated like\n>> that. However, for any code path relying on a page read without any\n>> locking insurance, we cannot really have a lot of trust in any of the\n>> fields assigned to the page as this could just be random corruption\n>> garbage, and the only thing I am ready to trust here a checksum\n>> mismatch check, because that's the only field on the page that's\n>> linked to its full contents on the 8k page. This also keeps the code\n>> simpler.\n> A small update here. I have extracted the refactored part for\n> PageIsVerified() and committed it as that's independently useful.\n> This makes the patch proposed here simpler on HEAD, leading to the\n> attached.\n> --\n> Michael\n\nThank you for committing the first part.\n\nIn case you need a second opinion on the remaining patch, it still looks \ngood to me.\n\n-- \nAnastasia Lubennikova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Tue, 27 Oct 2020 22:56:23 +0300", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "On Tue, Oct 27, 2020 at 10:56:23PM +0300, Anastasia Lubennikova wrote:\n> In case you need a second opinion on the remaining patch, it still looks\n> good to me.\n\nThanks. The patch for v13 cannot use a macro, but one of the versions\nof upthread would do just fine. I have been wondering about using the\nnew CheckBuffer() for the purpose of the retry to make it\nconcurrent-safe, but by looking at the code I think that we would run\nunto problems when trying to open through smgr.c any relation file in\nglobal/ as these require an invalid backend ID, and a WAL sender does\nnot satisfy that (see the assertion in GetRelationPath()). I have\nbeen hesitating about increasing the number of retries though to give\nmore room to false positives. 20 perhaps? That would give 2s to a\ndisk to finish flushing a page that was caught in the middle of a\ncheck with a sleep of 100ms, which sounds plenty enough.\n--\nMichael", "msg_date": "Wed, 28 Oct 2020 16:11:56 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "On Wed, Oct 28, 2020 at 04:11:56PM +0900, Michael Paquier wrote:\n> Thanks. The patch for v13 cannot use a macro, but one of the versions\n> of upthread would do just fine. I have been wondering about using the\n> new CheckBuffer() for the purpose of the retry to make it\n> concurrent-safe, but by looking at the code I think that we would run\n> unto problems when trying to open through smgr.c any relation file in\n> global/ as these require an invalid backend ID, and a WAL sender does\n> not satisfy that (see the assertion in GetRelationPath()).\n\nActually, scratch that.. It looks like I am wrong here. By using\nsmgropen() with InvalidBackendId and a RelFileNode built using the\npath of the file being sent, similarly to what pg_rewind is doing in\nisRelDataFile(), we should have everything that's needed. This is\ntoo complicated for a backpatch and we should have some consolidation\nwith pg_rewind, so using the sleep/retry for v13 sounds like a safer\npath to take in the stable branch.\n--\nMichael", "msg_date": "Wed, 28 Oct 2020 16:43:44 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" }, { "msg_contents": "On Wed, Oct 28, 2020 at 04:43:44PM +0900, Michael Paquier wrote:\n> On Wed, Oct 28, 2020 at 04:11:56PM +0900, Michael Paquier wrote:\n>> Thanks. The patch for v13 cannot use a macro, but one of the versions\n>> of upthread would do just fine.\n\nFor the note, I have posted a set of patches to address all issues on\nthe original thread where the problem applies:\nhttps://www.postgresql.org/message-id/20201030023028.GC1693%40paquier.xyz\n--\nMichael", "msg_date": "Fri, 30 Oct 2020 11:33:42 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [patch] Fix checksum verification in base backups for zero page\n headers" } ]
[ { "msg_contents": "Hi, hackers\r\n\r\nWhen I setup a stream replication I found that the documentation says that promote_trigger_file\r\nparameter can only be set in the postgresql.conf file or on the server command line, however, it\r\ncan also be put into postgresql.auto.conf. If I use include to import a new config, it works too.\r\n\r\nThere are many parameters use this description:\r\n$ grep 'This parameter can only be set in the' -rn doc/\r\ndoc/src/sgml/sepgsql.sgml:273: This parameter can only be set in the <filename>postgresql.conf</filename>\r\ndoc/src/sgml/config.sgml:1001: This parameter can only be set in the <filename>postgresql.conf</filename>\r\ndoc/src/sgml/config.sgml:1040: for details. This parameter can only be set in the\r\ndoc/src/sgml/config.sgml:1071: This parameter can only be set in the <filename>postgresql.conf</filename>\r\ndoc/src/sgml/config.sgml:1133: This parameter can only be set in the <filename>postgresql.conf</filename>\r\ndoc/src/sgml/config.sgml:1151: This parameter can only be set in the <filename>postgresql.conf</filename>\r\ndoc/src/sgml/config.sgml:1169: This parameter can only be set in the <filename>postgresql.conf</filename>\r\ndoc/src/sgml/config.sgml:1187: This parameter can only be set in the <filename>postgresql.conf</filename>\r\ndoc/src/sgml/config.sgml:1204: This parameter can only be set in the <filename>postgresql.conf</filename>\r\ndoc/src/sgml/config.sgml:1232: This parameter can only be set in the\r\ndoc/src/sgml/config.sgml:1307: This parameter can only be set in the <filename>postgresql.conf</filename>\r\ndoc/src/sgml/config.sgml:1334: This parameter can only be set in the <filename>postgresql.conf</filename>\r\ndoc/src/sgml/config.sgml:1411: This parameter can only be set in the <filename>postgresql.conf</filename>\r\ndoc/src/sgml/config.sgml:1445: This parameter can only be set in the <filename>postgresql.conf</filename>\r\ndoc/src/sgml/config.sgml:1471: This parameter can only be set in the <filename>postgresql.conf</filename>\r\ndoc/src/sgml/config.sgml:2180: of 10. This parameter can only be set in the\r\ndoc/src/sgml/config.sgml:2199: This parameter can only be set in the <filename>postgresql.conf</filename>\r\ndoc/src/sgml/config.sgml:2227: This parameter can only be set in the <filename>postgresql.conf</filename>\r\ndoc/src/sgml/config.sgml:2259: This parameter can only be set in the <filename>postgresql.conf</filename>\r\ndoc/src/sgml/config.sgml:2817: This parameter can only be set in the <filename>postgresql.conf</filename>\r\ndoc/src/sgml/config.sgml:2863: This parameter can only be set in the <filename>postgresql.conf</filename>\r\ndoc/src/sgml/config.sgml:3012: next higher multiple of 10. This parameter can only be set in the\r\ndoc/src/sgml/config.sgml:3036: This parameter can only be set in the\r\n….\r\n\r\nI think this description is misleading. we should correct it, isn't it?\r\n\r\nRegards,\r\nJapin Li\r\n\n\n\n\n\n\r\nHi, hackers\r\n\n\nWhen I setup a stream replication I found that the documentation says that promote_trigger_file\nparameter can only be set in the postgresql.conf file or on the server command line, however, it\ncan also be put into postgresql.auto.conf. If I use include to import a new config, it works too.\n\n\nThere are many parameters use this description:\n\n$ grep 'This parameter can only be set in the' -rn doc/\ndoc/src/sgml/sepgsql.sgml:273:      This parameter can only be set in the <filename>postgresql.conf</filename>\ndoc/src/sgml/config.sgml:1001:        This parameter can only be set in the <filename>postgresql.conf</filename>\ndoc/src/sgml/config.sgml:1040:        for details. This parameter can only be set in the\ndoc/src/sgml/config.sgml:1071:        This parameter can only be set in the <filename>postgresql.conf</filename>\ndoc/src/sgml/config.sgml:1133:        This parameter can only be set in the <filename>postgresql.conf</filename>\ndoc/src/sgml/config.sgml:1151:        This parameter can only be set in the <filename>postgresql.conf</filename>\ndoc/src/sgml/config.sgml:1169:        This parameter can only be set in the <filename>postgresql.conf</filename>\ndoc/src/sgml/config.sgml:1187:        This parameter can only be set in the <filename>postgresql.conf</filename>\ndoc/src/sgml/config.sgml:1204:        This parameter can only be set in the <filename>postgresql.conf</filename>\ndoc/src/sgml/config.sgml:1232:        This parameter can only be set in the\ndoc/src/sgml/config.sgml:1307:        This parameter can only be set in the <filename>postgresql.conf</filename>\ndoc/src/sgml/config.sgml:1334:        This parameter can only be set in the <filename>postgresql.conf</filename>\ndoc/src/sgml/config.sgml:1411:        This parameter can only be set in the <filename>postgresql.conf</filename>\ndoc/src/sgml/config.sgml:1445:        This parameter can only be set in the <filename>postgresql.conf</filename>\ndoc/src/sgml/config.sgml:1471:        This parameter can only be set in the <filename>postgresql.conf</filename>\ndoc/src/sgml/config.sgml:2180:         of 10.  This parameter can only be set in the\ndoc/src/sgml/config.sgml:2199:         This parameter can only be set in the <filename>postgresql.conf</filename>\ndoc/src/sgml/config.sgml:2227:         This parameter can only be set in the <filename>postgresql.conf</filename>\ndoc/src/sgml/config.sgml:2259:         This parameter can only be set in the <filename>postgresql.conf</filename>\ndoc/src/sgml/config.sgml:2817:        This parameter can only be set in the <filename>postgresql.conf</filename>\ndoc/src/sgml/config.sgml:2863:        This parameter can only be set in the <filename>postgresql.conf</filename>\ndoc/src/sgml/config.sgml:3012:        next higher multiple of 10. This parameter can only be set in the\ndoc/src/sgml/config.sgml:3036:        This parameter can only be set in the\n\n….\n\n\nI think this description is misleading. we should correct it, isn't it?\n\n\nRegards,\nJapin Li", "msg_date": "Tue, 1 Sep 2020 10:37:40 +0000", "msg_from": "Li Japin <japinli@hotmail.com>", "msg_from_op": true, "msg_subject": "Docs: inaccurate description about config settings" }, { "msg_contents": "2020年9月1日(火) 19:37 Li Japin <japinli@hotmail.com>:\n>\n> Hi, hackers\n>\n> When I setup a stream replication I found that the documentation says that promote_trigger_file\n> parameter can only be set in the postgresql.conf file or on the server command line, however, it\n> can also be put into postgresql.auto.conf. If I use include to import a new config, it works too.\n>\n> There are many parameters use this description:\n> $ grep 'This parameter can only be set in the' -rn doc/\n(...)\n>\n> I think this description is misleading. we should correct it, isn't it?\n\nI must admit every time I see this wording, it strikes me as very specific\nand potentially confusing given the alternative files the parameter could be\nplaced in.\n\nI think it would be clearer for anyone not familiar with the configuration file\nsystem to change occurrences of this wording to something like:\n\n This parameter can only be set in the <link\nlinkend=\"config-setting-configuration-file\">configuration file</link>\n\nwhich would link to:\n\n https://www.postgresql.org/docs/current/config-setting.html#CONFIG-SETTING-CONFIGURATION-FILE\n\nwhich provides more information. Though on that page it seems like it would be\nalso sensible to bundle the section about include directives in the\nconfiguration\nfile (19.1.5) together with the section about the configuration itself (19.1.2).\n\n\nRegards\n\nIan Barwick\n\n-- \nIan Barwick https://www.2ndQuadrant.com/\n PostgreSQL Development, 24x7 Support, Training & Services\n\n\n", "msg_date": "Tue, 1 Sep 2020 21:20:41 +0900", "msg_from": "Ian Lawrence Barwick <barwick@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Docs: inaccurate description about config settings" }, { "msg_contents": "On Sep 1, 2020, at 8:20 PM, Ian Lawrence Barwick <barwick@gmail.com<mailto:barwick@gmail.com>> wrote:\r\n\r\n2020年9月1日(火) 19:37 Li Japin <japinli@hotmail.com<mailto:japinli@hotmail.com>>:\r\n\r\nHi, hackers\r\n\r\nWhen I setup a stream replication I found that the documentation says that promote_trigger_file\r\nparameter can only be set in the postgresql.conf file or on the server command line, however, it\r\ncan also be put into postgresql.auto.conf. If I use include to import a new config, it works too.\r\n\r\nThere are many parameters use this description:\r\n$ grep 'This parameter can only be set in the' -rn doc/\r\n(...)\r\n\r\nI think this description is misleading. we should correct it, isn't it?\r\n\r\nI must admit every time I see this wording, it strikes me as very specific\r\nand potentially confusing given the alternative files the parameter could be\r\nplaced in.\r\n\r\nI think it would be clearer for anyone not familiar with the configuration file\r\nsystem to change occurrences of this wording to something like:\r\n\r\n This parameter can only be set in the <link\r\nlinkend=\"config-setting-configuration-file\">configuration file</link>\r\n\r\nwhich would link to:\r\n\r\n https://www.postgresql.org/docs/current/config-setting.html#CONFIG-SETTING-CONFIGURATION-FILE\r\n\r\nwhich provides more information. Though on that page it seems like it would be\r\nalso sensible to bundle the section about include directives in the\r\nconfiguration\r\nfile (19.1.5) together with the section about the configuration itself (19.1.2).\r\n\r\n+1\r\n\r\nAttached is a fix following Ian Barwick’s suggestion.\r\n\r\nRegards,\r\nJapin Li", "msg_date": "Tue, 1 Sep 2020 15:06:19 +0000", "msg_from": "Li Japin <japinli@hotmail.com>", "msg_from_op": true, "msg_subject": "Re: Docs: inaccurate description about config settings" } ]
[ { "msg_contents": "Hi,\n\nBetter late than never, to follow up on the original thread [1] I would like to\ncontinue the discussion with the another version of the patch for group by\nreordering optimization. To remind, it's about reordering of group by clauses\nto do sorting more efficiently. The patch is rebased and modified to address\n(at least partially) the suggestions about making it consider new additional\npaths instead of changing original ones. It is still pretty much\nproof-of-concept version though with many blind spots, but I wanted to start\nkicking it and post at least something, otherwise it will never happen. An\nincremental approach so to say.\n\nIn many ways it still contains the original code from Teodor. Changes and notes:\n\n* Instead of changing the order directly, now patch creates another patch with\n modifier order of clauses. It does so for the normal sort as well as for\n incremental sort. The whole thing is done in two steps: first it finds a\n potentially better ordering taking into account number of groups, widths and\n comparison costs; afterwards this information is used to produce a cost\n estimation. This is implemented via a separate create_reordered_sort_path to\n not introduce too many changes, I couldn't find any better place.\n\n* Function get_func_cost was removed at some point, but unfortunately this\n patch was implemented before that, so it's still present there.\n\n* For simplicity I've removed support in create_partial_grouping_paths, since\n they were not covered by the existing tests anyway.\n\n* The costing part is pretty rudimentary and looks only at the first group.\n It's mostly hand crafted to pass the existing tests.\n\nThe question about handling skewed data sets is not addressed yet.\n\n[1]: https://www.postgresql.org/message-id/flat/7c79e6a5-8597-74e8-0671-1c39d124c9d6%40sigaev.ru", "msg_date": "Tue, 1 Sep 2020 13:15:31 +0200", "msg_from": "Dmitry Dolgov <9erthalion6@gmail.com>", "msg_from_op": true, "msg_subject": "Group by reordering optimization" }, { "msg_contents": "On Tue, Sep 01, 2020 at 01:15:31PM +0200, Dmitry Dolgov wrote:\n>Hi,\n>\n>Better late than never, to follow up on the original thread [1] I would like to\n>continue the discussion with the another version of the patch for group by\n>reordering optimization. To remind, it's about reordering of group by clauses\n>to do sorting more efficiently. The patch is rebased and modified to address\n>(at least partially) the suggestions about making it consider new additional\n>paths instead of changing original ones. It is still pretty much\n>proof-of-concept version though with many blind spots, but I wanted to start\n>kicking it and post at least something, otherwise it will never happen. An\n>incremental approach so to say.\n>\n>In many ways it still contains the original code from Teodor. Changes and notes:\n>\n>* Instead of changing the order directly, now patch creates another patch with\n> modifier order of clauses. It does so for the normal sort as well as for\n> incremental sort. The whole thing is done in two steps: first it finds a\n> potentially better ordering taking into account number of groups, widths and\n> comparison costs; afterwards this information is used to produce a cost\n> estimation. This is implemented via a separate create_reordered_sort_path to\n> not introduce too many changes, I couldn't find any better place.\n>\n\nI haven't tested the patch with any queries, but I agree this seems like\nthe right approach in general.\n\nI'm a bit worried about how complex the code in planner.c is getting -\nthe incremental sort patch already made it a bit too complex, and this\nis just another step in that direction. I suppose we should refactor\nadd_paths_to_grouping_rel() by breaking it into smaller / more readable\npieces ...\n\n>* Function get_func_cost was removed at some point, but unfortunately this\n> patch was implemented before that, so it's still present there.\n>\n>* For simplicity I've removed support in create_partial_grouping_paths, since\n> they were not covered by the existing tests anyway.\n>\n\nHmmm, OK. I think that's something we'll need to address for the final\npatch, but I agree we can add it after improving the costing etc.\n\n>* The costing part is pretty rudimentary and looks only at the first group.\n> It's mostly hand crafted to pass the existing tests.\n>\n\nOK, understood.\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, 1 Sep 2020 23:08:54 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Group by reordering optimization" }, { "msg_contents": "On Tue, Sep 1, 2020 at 2:09 PM Tomas Vondra\n<tomas.vondra@2ndquadrant.com> wrote:\n> >* Instead of changing the order directly, now patch creates another patch with\n> > modifier order of clauses. It does so for the normal sort as well as for\n> > incremental sort. The whole thing is done in two steps: first it finds a\n> > potentially better ordering taking into account number of groups, widths and\n> > comparison costs; afterwards this information is used to produce a cost\n> > estimation. This is implemented via a separate create_reordered_sort_path to\n> > not introduce too many changes, I couldn't find any better place.\n> >\n>\n> I haven't tested the patch with any queries, but I agree this seems like\n> the right approach in general.\n\nIf we're creating a new sort path anyway, then perhaps we can also\nchange the collation -- it might be possible to \"reduce\" it to the \"C\"\ncollation without breaking queries.\n\nThis is admittedly pretty hard to do well. It could definitely work\nout when we have to do a sort anyway -- a sort with high cardinality\nabbreviated keys will be very fast (though we can't use abbreviated\nkeys with libc collations right now). OTOH, it would be quite\ncounterproductive if we were hoping to get an incremental sort that\nused some available index that happens to use the default collation\n(which is not the C collation in cases where this optimization is\nexpected to help).\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Tue, 1 Sep 2020 15:09:14 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: Group by reordering optimization" }, { "msg_contents": "On Tue, Sep 01, 2020 at 03:09:14PM -0700, Peter Geoghegan wrote:\n>On Tue, Sep 1, 2020 at 2:09 PM Tomas Vondra\n><tomas.vondra@2ndquadrant.com> wrote:\n>> >* Instead of changing the order directly, now patch creates another patch with\n>> > modifier order of clauses. It does so for the normal sort as well as for\n>> > incremental sort. The whole thing is done in two steps: first it finds a\n>> > potentially better ordering taking into account number of groups, widths and\n>> > comparison costs; afterwards this information is used to produce a cost\n>> > estimation. This is implemented via a separate create_reordered_sort_path to\n>> > not introduce too many changes, I couldn't find any better place.\n>> >\n>>\n>> I haven't tested the patch with any queries, but I agree this seems like\n>> the right approach in general.\n>\n>If we're creating a new sort path anyway, then perhaps we can also\n>change the collation -- it might be possible to \"reduce\" it to the \"C\"\n>collation without breaking queries.\n>\n>This is admittedly pretty hard to do well. It could definitely work\n>out when we have to do a sort anyway -- a sort with high cardinality\n>abbreviated keys will be very fast (though we can't use abbreviated\n>keys with libc collations right now). OTOH, it would be quite\n>counterproductive if we were hoping to get an incremental sort that\n>used some available index that happens to use the default collation\n>(which is not the C collation in cases where this optimization is\n>expected to help).\n>\n\nEven if reducing collations like this was possible (I have no idea how\ntricky it is, my knowledge of collations is pretty minimal and from what\nI know I'm not dying to learn more), I suggest we consider that out of\nscope for this particular patch.\n\nThere are multiple open issues already - deciding which pathkeys are\ninteresting, reasonable costing, etc. Once those issues are solved, we\ncan consider tweaking collations as an additional optimizations.\n\nOr maybe we can consider it entirely separately, i.e. why would it\nmatter if we re-order the GROUP BY keys? The collation reduction can\njust as well help even if we use the same pathkeys.\n\n\nregards\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 2 Sep 2020 18:12:01 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Group by reordering optimization" }, { "msg_contents": "> On Tue, Sep 01, 2020 at 11:08:54PM +0200, Tomas Vondra wrote:\n> On Tue, Sep 01, 2020 at 01:15:31PM +0200, Dmitry Dolgov wrote:\n> > Hi,\n> > \n> > Better late than never, to follow up on the original thread [1] I would like to\n> > continue the discussion with the another version of the patch for group by\n> > reordering optimization. To remind, it's about reordering of group by clauses\n> > to do sorting more efficiently. The patch is rebased and modified to address\n> > (at least partially) the suggestions about making it consider new additional\n> > paths instead of changing original ones. It is still pretty much\n> > proof-of-concept version though with many blind spots, but I wanted to start\n> > kicking it and post at least something, otherwise it will never happen. An\n> > incremental approach so to say.\n> > \n> > In many ways it still contains the original code from Teodor. Changes and notes:\n> > \n> > * Instead of changing the order directly, now patch creates another patch with\n> > modifier order of clauses. It does so for the normal sort as well as for\n> > incremental sort. The whole thing is done in two steps: first it finds a\n> > potentially better ordering taking into account number of groups, widths and\n> > comparison costs; afterwards this information is used to produce a cost\n> > estimation. This is implemented via a separate create_reordered_sort_path to\n> > not introduce too many changes, I couldn't find any better place.\n> > \n> \n> I haven't tested the patch with any queries, but I agree this seems like\n> the right approach in general.\n> \n> I'm a bit worried about how complex the code in planner.c is getting -\n> the incremental sort patch already made it a bit too complex, and this\n> is just another step in that direction. I suppose we should refactor\n> add_paths_to_grouping_rel() by breaking it into smaller / more readable\n> pieces ...\n\nYes, that was my impression as well. I'll try to make such refactoring\neither as a separate patch or a part of the main one.\n\n> > * Function get_func_cost was removed at some point, but unfortunately this\n> > patch was implemented before that, so it's still present there.\n> > \n> > * For simplicity I've removed support in create_partial_grouping_paths, since\n> > they were not covered by the existing tests anyway.\n> > \n> \n> Hmmm, OK. I think that's something we'll need to address for the final\n> patch, but I agree we can add it after improving the costing etc.\n\nSure, I plan to return it in time. IIUC in the original patch series\nthis code wasn't covered with tests, so I've decided to minimize the\nchanges.\n\n\n", "msg_date": "Wed, 16 Sep 2020 16:20:39 +0200", "msg_from": "Dmitry Dolgov <9erthalion6@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Group by reordering optimization" }, { "msg_contents": "On 9/2/20 9:12 PM, Tomas Vondra wrote:\n > We could simply use the input \"tuples\" value here, and then divide the\n > current and previous estimate to calculate the number of new groups.\n\nPerforming a review of this patch I made a number of changes (see \ncleanup.txt). Maybe it will be useful.\nAs I see, the code, which implements the main idea, is quite stable. \nDoubts localized in the cost estimation routine. Maybe try to finish \nthis work by implementing an conservative strategy to a cost estimation \nof sorting?\n\n-- \nregards,\nAndrey Lepikhov\nPostgres Professional", "msg_date": "Tue, 28 Dec 2021 13:47:35 +0500", "msg_from": "\"Andrey V. Lepikhov\" <a.lepikhov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: POC: GROUP BY optimization" } ]
[ { "msg_contents": "Hi,\n\nthe pg_checksums docs mention that \"When enabling checksums, every file\nin the cluster is rewritten\".\n\n From IRC discussions, \"rewritten\" seems ambiguous, it could mean that a\nsecond copy of the file is written and then switched over, implying\nincreased storage demand during the operation.\n\nSo maybe \"rewritten in-place\" is better, as per the attached?\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", "msg_date": "Tue, 01 Sep 2020 15:13:58 +0200", "msg_from": "Michael Banck <michael.banck@credativ.de>", "msg_from_op": true, "msg_subject": "clarify \"rewritten\" in pg_checksums docs" }, { "msg_contents": "> On 1 Sep 2020, at 15:13, Michael Banck <michael.banck@credativ.de> wrote:\n\n> the pg_checksums docs mention that \"When enabling checksums, every file\n> in the cluster is rewritten\".\n> \n> From IRC discussions, \"rewritten\" seems ambiguous, it could mean that a\n> second copy of the file is written and then switched over, implying\n> increased storage demand during the operation.\n\nMakes sense, I can see that confusion.\n\n> So maybe \"rewritten in-place\" is better, as per the attached?\n\nIsn't \"modified in-place\" a more accurate description of the process?\n\ncheers ./daniel\n\n\n", "msg_date": "Tue, 1 Sep 2020 15:29:17 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: clarify \"rewritten\" in pg_checksums docs" }, { "msg_contents": "Hi,\n\nAm Dienstag, den 01.09.2020, 15:29 +0200 schrieb Daniel Gustafsson:\n> > On 1 Sep 2020, at 15:13, Michael Banck <michael.banck@credativ.de> wrote:\n> > the pg_checksums docs mention that \"When enabling checksums, every file\n> > in the cluster is rewritten\".\n> > \n> > From IRC discussions, \"rewritten\" seems ambiguous, it could mean that a\n> > second copy of the file is written and then switched over, implying\n> > increased storage demand during the operation.\n> \n> Makes sense, I can see that confusion.\n> \n> > So maybe \"rewritten in-place\" is better, as per the attached?\n> \n> Isn't \"modified in-place\" a more accurate description of the process?\n\nAIUI we do rewrite the whole file (block by block, after updating the\npage header with the checksum), so yeah, I though about using modified\ninstead but then decided rewritten is pretty (or even more) accurate.\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": "Tue, 01 Sep 2020 15:34:11 +0200", "msg_from": "Michael Banck <michael.banck@credativ.de>", "msg_from_op": true, "msg_subject": "Re: clarify \"rewritten\" in pg_checksums docs" }, { "msg_contents": "> On 1 Sep 2020, at 15:34, Michael Banck <michael.banck@credativ.de> wrote:\n> Am Dienstag, den 01.09.2020, 15:29 +0200 schrieb Daniel Gustafsson:\n\n>> Isn't \"modified in-place\" a more accurate description of the process?\n> \n> AIUI we do rewrite the whole file (block by block, after updating the\n> page header with the checksum), so yeah, I though about using modified\n> instead but then decided rewritten is pretty (or even more) accurate.\n\nWell, I was thinking less technically accurate and more descriptive for end\nusers, hiding the implementation details. \"Rewrite\" sounds to me more like\nchanging data rather than amending pages with a checksum keeping data intact.\nEither way, adding \"in-place\" is an improvement IMO.\n\ncheers ./daniel\n\n\n", "msg_date": "Tue, 1 Sep 2020 15:44:06 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: clarify \"rewritten\" in pg_checksums docs" }, { "msg_contents": "On Tue, Sep 01, 2020 at 03:44:06PM +0200, Daniel Gustafsson wrote:\n> Well, I was thinking less technically accurate and more descriptive for end\n> users, hiding the implementation details. \"Rewrite\" sounds to me more like\n> changing data rather than amending pages with a checksum keeping data intact.\n> Either way, adding \"in-place\" is an improvement IMO.\n\nUsing rewritten still sounds more adapted to me, as we still write the\nthing with chunks of size BLCKSZ. No objections with the addition of\n\"in-place\" for that sentence. Any extra opinions?\n--\nMichael", "msg_date": "Wed, 2 Sep 2020 17:26:16 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: clarify \"rewritten\" in pg_checksums docs" }, { "msg_contents": "On Wed, Sep 02, 2020 at 05:26:16PM +0900, Michael Paquier wrote:\n> Using rewritten still sounds more adapted to me, as we still write the\n> thing with chunks of size BLCKSZ. No objections with the addition of\n> \"in-place\" for that sentence. Any extra opinions?\n\nSeeing no objections, I have applied the original patch of this thread\ndown to 12.\n--\nMichael", "msg_date": "Mon, 7 Sep 2020 15:00:20 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: clarify \"rewritten\" in pg_checksums docs" } ]
[ { "msg_contents": "I was experimenting with building with MIT Kerberos support on 64 bit\nWindows using MSVC and ran into a number of linker errors along the lines\nof:\n\n\"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgsql.sln\" (default target) (1) ->\n\"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\zic.vcxproj\" (default target) (2)\n->\n(Link target) ->\n LINK : fatal error LNK1181: cannot open input file\n'C:\\Progra~1\\MIT\\Kerberos\\lib.obj'\n[C:\\Users\\dpage\\Downloads\\postgresql-12.4\\zic.vcxproj]\n\nThat was after I had to manually add the include and lib paths in\nbuildenv.pl. Diving in a bit further I found a couple of things:\n\n1) The only buildfarm machine doing 64bit Windows Kerberos enabled builds\nwith MSVC is hammerkop. It enables it by setting the \"krb5\" option in\nconfig.pl, however, as far as I can see (going back to 9.5), the option is\nactually \"gss\". I can't see any sign in the log for the make step that it\nactually is making any attempt to build with Kerberos, despite the UI\nshowing the icon for it.\n\n2) I can't find anything in the MSVC build scripts in src/tools/msvc to\ndeal with 64bit Kerberos builds - Solution.pm seems to unconditionally try\nto link with the 32bit libraries (e.g. lib/i386/krb5_32.lib instead of\nlib/amd64/krb5_64.lib).\n\nI'm assuming noone has tried a build with 64bit Kerberos, or am I missing\nsomething?\n\nSidenote: I'm not sure even a 32bit Kerberos build will work, as\nSolution.pm assumes the headers are in $self->{options}->{gss} .\n'\\inc\\krb5', however in at least the latest installer from MIT they're\nactually in $self->{options}->{gss} . '\\include'.\n\n-- \nDave Page\nBlog: http://pgsnake.blogspot.com\nTwitter: @pgsnake\n\nEDB: http://www.enterprisedb.com\n\nI was experimenting with building with MIT Kerberos support on 64 bit Windows using MSVC and ran into a number of linker errors along the lines of:\"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgsql.sln\" (default target) (1) ->\"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\zic.vcxproj\" (default target) (2) ->(Link target) ->  LINK : fatal error LNK1181: cannot open input file 'C:\\Progra~1\\MIT\\Kerberos\\lib.obj' [C:\\Users\\dpage\\Downloads\\postgresql-12.4\\zic.vcxproj]That was after I had to manually add the include and lib paths in buildenv.pl. Diving in a bit further I found a couple of things:1) The only buildfarm machine doing 64bit Windows Kerberos enabled builds with MSVC is hammerkop. It enables it by setting the \"krb5\" option in config.pl, however, as far as I can see (going back to 9.5), the option is actually \"gss\". I can't see any sign in the log for the make step that it actually is making any attempt to build with Kerberos, despite the UI showing the icon for it.2) I can't find anything in the MSVC build scripts in src/tools/msvc to deal with 64bit Kerberos builds - Solution.pm seems to unconditionally try to link with the 32bit libraries (e.g. lib/i386/krb5_32.lib instead of lib/amd64/krb5_64.lib).I'm assuming noone has tried a build with 64bit Kerberos, or am I missing something?Sidenote: I'm not sure even a 32bit Kerberos build will work, as Solution.pm assumes the headers are in $self->{options}->{gss} . '\\inc\\krb5', however in at least the latest installer from MIT they're actually in $self->{options}->{gss} . '\\include'.-- Dave PageBlog: http://pgsnake.blogspot.comTwitter: @pgsnakeEDB: http://www.enterprisedb.com", "msg_date": "Tue, 1 Sep 2020 16:22:18 +0100", "msg_from": "Dave Page <dpage@pgadmin.org>", "msg_from_op": true, "msg_subject": "Kerberos support broken on MSVC builds for Windows x64?" }, { "msg_contents": "On Tue, Sep 1, 2020 at 4:22 PM Dave Page <dpage@pgadmin.org> wrote:\n\n> I was experimenting with building with MIT Kerberos support on 64 bit\n> Windows using MSVC and ran into a number of linker errors along the lines\n> of:\n>\n> \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgsql.sln\" (default target) (1)\n> ->\n> \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\zic.vcxproj\" (default target)\n> (2) ->\n> (Link target) ->\n> LINK : fatal error LNK1181: cannot open input file\n> 'C:\\Progra~1\\MIT\\Kerberos\\lib.obj'\n> [C:\\Users\\dpage\\Downloads\\postgresql-12.4\\zic.vcxproj]\n>\n> That was after I had to manually add the include and lib paths in\n> buildenv.pl. Diving in a bit further I found a couple of things:\n>\n> 1) The only buildfarm machine doing 64bit Windows Kerberos enabled builds\n> with MSVC is hammerkop. It enables it by setting the \"krb5\" option in\n> config.pl, however, as far as I can see (going back to 9.5), the option\n> is actually \"gss\". I can't see any sign in the log for the make step that\n> it actually is making any attempt to build with Kerberos, despite the UI\n> showing the icon for it.\n>\n> 2) I can't find anything in the MSVC build scripts in src/tools/msvc to\n> deal with 64bit Kerberos builds - Solution.pm seems to unconditionally try\n> to link with the 32bit libraries (e.g. lib/i386/krb5_32.lib instead of\n> lib/amd64/krb5_64.lib).\n>\n> I'm assuming noone has tried a build with 64bit Kerberos, or am I missing\n> something?\n>\n> Sidenote: I'm not sure even a 32bit Kerberos build will work, as\n> Solution.pm assumes the headers are in $self->{options}->{gss} .\n> '\\inc\\krb5', however in at least the latest installer from MIT they're\n> actually in $self->{options}->{gss} . '\\include'.\n>\n\nAttached is a patch against 12.4 for the build system in case anyone wants\nto play (I'll do it properly against the head branch later). I'm guessing\nthis will work for < 12, as with 12 I'm now getting the following which\nlooks like it's related to GSS encryption:\n\n\"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgsql.sln\" (default target) (1) ->\n\"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgcrypto.vcxproj\" (default\ntarget) (2) ->\n\"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj\" (default\ntarget) (3) ->\n(Link target) ->\n be-secure-gssapi.obj : error LNK2019: unresolved external symbol setenv\nreferenced in function secure_open_gssapi\n[C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj]\n .\\Release\\postgres\\postgres.exe : fatal error LNK1120: 1 unresolved\nexternals [C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj]\n\nI'll dig into that some more.\n\n-- \nDave Page\nBlog: http://pgsnake.blogspot.com\nTwitter: @pgsnake\n\nEDB: http://www.enterprisedb.com", "msg_date": "Tue, 1 Sep 2020 17:12:17 +0100", "msg_from": "Dave Page <dpage@pgadmin.org>", "msg_from_op": true, "msg_subject": "Re: Kerberos support broken on MSVC builds for Windows x64?" }, { "msg_contents": "Greetings,\n\n* Dave Page (dpage@pgadmin.org) wrote:\n> Attached is a patch against 12.4 for the build system in case anyone wants\n> to play (I'll do it properly against the head branch later). I'm guessing\n> this will work for < 12, as with 12 I'm now getting the following which\n> looks like it's related to GSS encryption:\n> \n> \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgsql.sln\" (default target) (1) ->\n> \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgcrypto.vcxproj\" (default\n> target) (2) ->\n> \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj\" (default\n> target) (3) ->\n> (Link target) ->\n> be-secure-gssapi.obj : error LNK2019: unresolved external symbol setenv\n> referenced in function secure_open_gssapi\n> [C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj]\n> .\\Release\\postgres\\postgres.exe : fatal error LNK1120: 1 unresolved\n> externals [C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj]\n> \n> I'll dig into that some more.\n\nYes, that'd be in the GSSENC code, which I hadn't been expecting to be\nused under Windows. If you're successful, I don't have any issue\nhelping to make that work, though I'm curious if you're trying to build\nwith MIT KfW (which is rather ancient these days, being based on krb5\n1.13 and not updated since..) or with a more current release...?\n\nOf course, it'd be good to get a buildfarm animal in place that's\nactually testing this if we're going to make it work.\n\nRegarding the setenv() call, should be able to use pgwin32_putenv() in\nplace on Windows, I'd think..?\n\nThanks,\n\nStephen", "msg_date": "Tue, 1 Sep 2020 12:29:22 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Kerberos support broken on MSVC builds for Windows x64?" }, { "msg_contents": "Hi\n\nOn Tue, Sep 1, 2020 at 5:29 PM Stephen Frost <sfrost@snowman.net> wrote:\n\n> Greetings,\n>\n> * Dave Page (dpage@pgadmin.org) wrote:\n> > Attached is a patch against 12.4 for the build system in case anyone\n> wants\n> > to play (I'll do it properly against the head branch later). I'm guessing\n> > this will work for < 12, as with 12 I'm now getting the following which\n> > looks like it's related to GSS encryption:\n> >\n> > \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgsql.sln\" (default target)\n> (1) ->\n> > \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgcrypto.vcxproj\" (default\n> > target) (2) ->\n> > \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj\" (default\n> > target) (3) ->\n> > (Link target) ->\n> > be-secure-gssapi.obj : error LNK2019: unresolved external symbol setenv\n> > referenced in function secure_open_gssapi\n> > [C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj]\n> > .\\Release\\postgres\\postgres.exe : fatal error LNK1120: 1 unresolved\n> > externals [C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj]\n> >\n> > I'll dig into that some more.\n>\n> Yes, that'd be in the GSSENC code, which I hadn't been expecting to be\n> used under Windows. If you're successful, I don't have any issue\n> helping to make that work, though I'm curious if you're trying to build\n> with MIT KfW (which is rather ancient these days, being based on krb5\n> 1.13 and not updated since..) or with a more current release...?\n>\n\nI'm currently using the KFW 4.1 build from MIT. I've tried building it\nmyself but it requires a very old toolchain (which defeated the point of\nwhat I was trying to do at the time).\n\nI haven't yet looked to see if the source for krb5-1.8.2 will build or even\nhas the right bits in it for Windows - as I'm sure you know MIT seem to\nmaintain an entirely different version for Windows for which I assume\nthere's a reason.\n\n\n>\n> Of course, it'd be good to get a buildfarm animal in place that's\n> actually testing this if we're going to make it work.\n>\n\nFixing the config on hamerkop should deal with that I think. Though I am\nconfused as to why the Buildfarm UI thinks it has Kerberos support enabled\n- did we change the config parameter from krb5 to gss some time prior to\n9.5? If so, that could explain it.\n\n\n>\n> Regarding the setenv() call, should be able to use pgwin32_putenv() in\n> place on Windows, I'd think..?\n>\n\nRight, I imagine so. It's on my todo...\n\n\n-- \nDave Page\nBlog: http://pgsnake.blogspot.com\nTwitter: @pgsnake\n\nEDB: http://www.enterprisedb.com\n\nHiOn Tue, Sep 1, 2020 at 5:29 PM Stephen Frost <sfrost@snowman.net> wrote:Greetings,\n\n* Dave Page (dpage@pgadmin.org) wrote:\n> Attached is a patch against 12.4 for the build system in case anyone wants\n> to play (I'll do it properly against the head branch later). I'm guessing\n> this will work for < 12, as with 12 I'm now getting the following which\n> looks like it's related to GSS encryption:\n> \n> \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgsql.sln\" (default target) (1) ->\n> \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgcrypto.vcxproj\" (default\n> target) (2) ->\n> \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj\" (default\n> target) (3) ->\n> (Link target) ->\n>   be-secure-gssapi.obj : error LNK2019: unresolved external symbol setenv\n> referenced in function secure_open_gssapi\n> [C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj]\n>   .\\Release\\postgres\\postgres.exe : fatal error LNK1120: 1 unresolved\n> externals [C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj]\n> \n> I'll dig into that some more.\n\nYes, that'd be in the GSSENC code, which I hadn't been expecting to be\nused under Windows.  If you're successful, I don't have any issue\nhelping to make that work, though I'm curious if you're trying to build\nwith MIT KfW (which is rather ancient these days, being based on krb5\n1.13 and not updated since..) or with a more current release...?I'm currently using the KFW 4.1 build from MIT. I've tried building it myself but it requires a very old toolchain (which defeated the point of what I was trying to do at the time).I haven't yet looked to see if the source for krb5-1.8.2 will build or even has the right bits in it for Windows - as I'm sure you know MIT seem to maintain an entirely different version for Windows for which I assume there's a reason. \n\nOf course, it'd be good to get a buildfarm animal in place that's\nactually testing this if we're going to make it work.Fixing the config on hamerkop should deal with that I think. Though I am confused as to why the Buildfarm UI thinks it has Kerberos support enabled - did we change the config parameter from krb5 to gss some time prior to 9.5? If so, that could explain it. \n\nRegarding the setenv() call, should be able to use pgwin32_putenv() in\nplace on Windows, I'd think..?Right, I imagine so. It's on my todo... -- Dave PageBlog: http://pgsnake.blogspot.comTwitter: @pgsnakeEDB: http://www.enterprisedb.com", "msg_date": "Wed, 2 Sep 2020 09:05:43 +0100", "msg_from": "Dave Page <dpage@pgadmin.org>", "msg_from_op": true, "msg_subject": "Re: Kerberos support broken on MSVC builds for Windows x64?" }, { "msg_contents": "Greetings,\n\n* Dave Page (dpage@pgadmin.org) wrote:\n> On Tue, Sep 1, 2020 at 5:29 PM Stephen Frost <sfrost@snowman.net> wrote:\n> > * Dave Page (dpage@pgadmin.org) wrote:\n> > > Attached is a patch against 12.4 for the build system in case anyone\n> > wants\n> > > to play (I'll do it properly against the head branch later). I'm guessing\n> > > this will work for < 12, as with 12 I'm now getting the following which\n> > > looks like it's related to GSS encryption:\n> > >\n> > > \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgsql.sln\" (default target)\n> > (1) ->\n> > > \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgcrypto.vcxproj\" (default\n> > > target) (2) ->\n> > > \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj\" (default\n> > > target) (3) ->\n> > > (Link target) ->\n> > > be-secure-gssapi.obj : error LNK2019: unresolved external symbol setenv\n> > > referenced in function secure_open_gssapi\n> > > [C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj]\n> > > .\\Release\\postgres\\postgres.exe : fatal error LNK1120: 1 unresolved\n> > > externals [C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj]\n> > >\n> > > I'll dig into that some more.\n> >\n> > Yes, that'd be in the GSSENC code, which I hadn't been expecting to be\n> > used under Windows. If you're successful, I don't have any issue\n> > helping to make that work, though I'm curious if you're trying to build\n> > with MIT KfW (which is rather ancient these days, being based on krb5\n> > 1.13 and not updated since..) or with a more current release...?\n> \n> I'm currently using the KFW 4.1 build from MIT. I've tried building it\n> myself but it requires a very old toolchain (which defeated the point of\n> what I was trying to do at the time).\n\n> I haven't yet looked to see if the source for krb5-1.8.2 will build or even\n> has the right bits in it for Windows - as I'm sure you know MIT seem to\n> maintain an entirely different version for Windows for which I assume\n> there's a reason.\n\nI'm a bit confused as to why you'd consider trying 1.8.2- did you mean\n1.18.2 there, perhaps..? That's what I would think to try, since, as I\nunderstand it from following the Kerberos Dev list (which is pretty\nresponsive...) has been updated to work with newer Windows build\ntoolchains.\n\n> > Of course, it'd be good to get a buildfarm animal in place that's\n> > actually testing this if we're going to make it work.\n> \n> Fixing the config on hamerkop should deal with that I think. Though I am\n> confused as to why the Buildfarm UI thinks it has Kerberos support enabled\n> - did we change the config parameter from krb5 to gss some time prior to\n> 9.5? If so, that could explain it.\n\nLooks to be run by SRA OSS.. Perhaps reaching out to them to ask about\nit would help?\n\n> > Regarding the setenv() call, should be able to use pgwin32_putenv() in\n> > place on Windows, I'd think..?\n> \n> Right, I imagine so. It's on my todo...\n\nAlright.\n\nThanks,\n\nStephen", "msg_date": "Wed, 2 Sep 2020 09:47:52 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Kerberos support broken on MSVC builds for Windows x64?" }, { "msg_contents": "Hi\n\nOn Wed, Sep 2, 2020 at 9:05 AM Dave Page <dpage@pgadmin.org> wrote:\n\n>\n>> Yes, that'd be in the GSSENC code, which I hadn't been expecting to be\n>> used under Windows.\n>\n>\nHere's a patch to make it build successfully (against head). I believe the\nchanges to Solution.pm should be back patched all the way, and the rest to\n12.\n\nTesting however, has been more problematic - I suspect at least partly\nbecause of my Kerberos newbie-ness. I have a test server in an Ubuntu VM,\nwhich I've used quite successfully to authenticate against another VM\nrunning PG 12 on Ubuntu, from both Ubuntu and Windows clients. Using that,\nbut with a Windows client running MIT Kerberos I find that getting a ticket\ntakes a good 30 seconds or so. Postgres also seems to get it's ticket\nsuccessfully via the keytab file:\n\nC:\\pg>\"c:\\Program Files\\MIT\\Kerberos\\bin\\klist.exe\"\nTicket cache: API:Initial default ccache\nDefault principal: dpage@PGADMIN.ORG\n\nValid starting Expires Service principal\n09/02/20 15:06:49 09/03/20 01:06:49 krbtgt/PGADMIN.ORG@PGADMIN.ORG\n renew until 09/03/20 15:06:31\n09/02/20 15:07:06 09/03/20 01:06:49 postgres/win-ilt1arj8a9c@\n renew until 09/03/20 15:06:31\n09/02/20 15:07:06 09/03/20 01:06:49 postgres/win-ilt1arj8a9c@PGADMIN.ORG\n renew until 09/03/20 15:06:31\n\nHowever, If I try to login using host + gss in the pg_hba.conf file, I then\nget:\n\nC:\\pg>bin\\psql postgres\npsql: error: could not connect to server: SSPI continuation error: No\ncredentials are available in the security package\n (8009030e)\n\nIf I try to use hostgssenc + gss, it looks like it's not even trying to\nencrypt:\n\nC:\\pg>bin\\psql postgres\npsql: error: could not connect to server: FATAL: no pg_hba.conf entry for\nhost \"::1\", user \"dpage\", database \"postgres\", SSL off\n\nAny ideas?\n\n\n-- \nDave Page\nBlog: http://pgsnake.blogspot.com\nTwitter: @pgsnake\n\nEDB: http://www.enterprisedb.com", "msg_date": "Wed, 2 Sep 2020 17:20:03 +0100", "msg_from": "Dave Page <dpage@pgadmin.org>", "msg_from_op": true, "msg_subject": "Re: Kerberos support broken on MSVC builds for Windows x64?" }, { "msg_contents": "On Wed, Sep 2, 2020 at 2:47 PM Stephen Frost <sfrost@snowman.net> wrote:\n\n> Greetings,\n>\n> * Dave Page (dpage@pgadmin.org) wrote:\n> > On Tue, Sep 1, 2020 at 5:29 PM Stephen Frost <sfrost@snowman.net> wrote:\n> > > * Dave Page (dpage@pgadmin.org) wrote:\n> > > > Attached is a patch against 12.4 for the build system in case anyone\n> > > wants\n> > > > to play (I'll do it properly against the head branch later). I'm\n> guessing\n> > > > this will work for < 12, as with 12 I'm now getting the following\n> which\n> > > > looks like it's related to GSS encryption:\n> > > >\n> > > > \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgsql.sln\" (default target)\n> > > (1) ->\n> > > > \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgcrypto.vcxproj\" (default\n> > > > target) (2) ->\n> > > > \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj\" (default\n> > > > target) (3) ->\n> > > > (Link target) ->\n> > > > be-secure-gssapi.obj : error LNK2019: unresolved external symbol\n> setenv\n> > > > referenced in function secure_open_gssapi\n> > > > [C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj]\n> > > > .\\Release\\postgres\\postgres.exe : fatal error LNK1120: 1 unresolved\n> > > > externals [C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj]\n> > > >\n> > > > I'll dig into that some more.\n> > >\n> > > Yes, that'd be in the GSSENC code, which I hadn't been expecting to be\n> > > used under Windows. If you're successful, I don't have any issue\n> > > helping to make that work, though I'm curious if you're trying to build\n> > > with MIT KfW (which is rather ancient these days, being based on krb5\n> > > 1.13 and not updated since..) or with a more current release...?\n> >\n> > I'm currently using the KFW 4.1 build from MIT. I've tried building it\n> > myself but it requires a very old toolchain (which defeated the point of\n> > what I was trying to do at the time).\n>\n> > I haven't yet looked to see if the source for krb5-1.8.2 will build or\n> even\n> > has the right bits in it for Windows - as I'm sure you know MIT seem to\n> > maintain an entirely different version for Windows for which I assume\n> > there's a reason.\n>\n> I'm a bit confused as to why you'd consider trying 1.8.2- did you mean\n> 1.18.2 there, perhaps..?\n\n\nYes, typo.\n\n\n> That's what I would think to try, since, as I\n> understand it from following the Kerberos Dev list (which is pretty\n> responsive...) has been updated to work with newer Windows build\n> toolchains.\n>\n\nOK, will try to do that tomorrow.\n\nThanks!\n\n\n>\n> > > Of course, it'd be good to get a buildfarm animal in place that's\n> > > actually testing this if we're going to make it work.\n> >\n> > Fixing the config on hamerkop should deal with that I think. Though I am\n> > confused as to why the Buildfarm UI thinks it has Kerberos support\n> enabled\n> > - did we change the config parameter from krb5 to gss some time prior to\n> > 9.5? If so, that could explain it.\n>\n> Looks to be run by SRA OSS.. Perhaps reaching out to them to ask about\n> it would help?\n>\n> > > Regarding the setenv() call, should be able to use pgwin32_putenv() in\n> > > place on Windows, I'd think..?\n> >\n> > Right, I imagine so. It's on my todo...\n>\n> Alright.\n>\n> Thanks,\n>\n> Stephen\n>\n\n\n-- \nDave Page\nBlog: http://pgsnake.blogspot.com\nTwitter: @pgsnake\n\nEDB: http://www.enterprisedb.com\n\nOn Wed, Sep 2, 2020 at 2:47 PM Stephen Frost <sfrost@snowman.net> wrote:Greetings,\n\n* Dave Page (dpage@pgadmin.org) wrote:\n> On Tue, Sep 1, 2020 at 5:29 PM Stephen Frost <sfrost@snowman.net> wrote:\n> > * Dave Page (dpage@pgadmin.org) wrote:\n> > > Attached is a patch against 12.4 for the build system in case anyone\n> > wants\n> > > to play (I'll do it properly against the head branch later). I'm guessing\n> > > this will work for < 12, as with 12 I'm now getting the following which\n> > > looks like it's related to GSS encryption:\n> > >\n> > > \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgsql.sln\" (default target)\n> > (1) ->\n> > > \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgcrypto.vcxproj\" (default\n> > > target) (2) ->\n> > > \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj\" (default\n> > > target) (3) ->\n> > > (Link target) ->\n> > >   be-secure-gssapi.obj : error LNK2019: unresolved external symbol setenv\n> > > referenced in function secure_open_gssapi\n> > > [C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj]\n> > >   .\\Release\\postgres\\postgres.exe : fatal error LNK1120: 1 unresolved\n> > > externals [C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj]\n> > >\n> > > I'll dig into that some more.\n> >\n> > Yes, that'd be in the GSSENC code, which I hadn't been expecting to be\n> > used under Windows.  If you're successful, I don't have any issue\n> > helping to make that work, though I'm curious if you're trying to build\n> > with MIT KfW (which is rather ancient these days, being based on krb5\n> > 1.13 and not updated since..) or with a more current release...?\n> \n> I'm currently using the KFW 4.1 build from MIT. I've tried building it\n> myself but it requires a very old toolchain (which defeated the point of\n> what I was trying to do at the time).\n\n> I haven't yet looked to see if the source for krb5-1.8.2 will build or even\n> has the right bits in it for Windows - as I'm sure you know MIT seem to\n> maintain an entirely different version for Windows for which I assume\n> there's a reason.\n\nI'm a bit confused as to why you'd consider trying 1.8.2- did you mean\n1.18.2 there, perhaps..?  Yes, typo. That's what I would think to try, since, as I\nunderstand it from following the Kerberos Dev list (which is pretty\nresponsive...) has been updated to work with newer Windows build\ntoolchains.OK, will try to do that tomorrow.Thanks! \n\n> > Of course, it'd be good to get a buildfarm animal in place that's\n> > actually testing this if we're going to make it work.\n> \n> Fixing the config on hamerkop should deal with that I think. Though I am\n> confused as to why the Buildfarm UI thinks it has Kerberos support enabled\n> - did we change the config parameter from krb5 to gss some time prior to\n> 9.5? If so, that could explain it.\n\nLooks to be run by SRA OSS..  Perhaps reaching out to them to ask about\nit would help?\n\n> > Regarding the setenv() call, should be able to use pgwin32_putenv() in\n> > place on Windows, I'd think..?\n> \n> Right, I imagine so. It's on my todo...\n\nAlright.\n\nThanks,\n\nStephen\n-- Dave PageBlog: http://pgsnake.blogspot.comTwitter: @pgsnakeEDB: http://www.enterprisedb.com", "msg_date": "Wed, 2 Sep 2020 17:21:06 +0100", "msg_from": "Dave Page <dpage@pgadmin.org>", "msg_from_op": true, "msg_subject": "Re: Kerberos support broken on MSVC builds for Windows x64?" }, { "msg_contents": "Greetings,\n\n* Dave Page (dpage@pgadmin.org) wrote:\n> On Wed, Sep 2, 2020 at 9:05 AM Dave Page <dpage@pgadmin.org> wrote:\n> >> Yes, that'd be in the GSSENC code, which I hadn't been expecting to be\n> >> used under Windows.\n>\n> Here's a patch to make it build successfully (against head). I believe the\n> changes to Solution.pm should be back patched all the way, and the rest to\n> 12.\n\nLooks about right.. I might pull out the code from both places that are\nsetting that variable into a dedicated function to be used from both\nthough.\n\n> Testing however, has been more problematic - I suspect at least partly\n> because of my Kerberos newbie-ness. I have a test server in an Ubuntu VM,\n> which I've used quite successfully to authenticate against another VM\n> running PG 12 on Ubuntu, from both Ubuntu and Windows clients. Using that,\n> but with a Windows client running MIT Kerberos I find that getting a ticket\n> takes a good 30 seconds or so. Postgres also seems to get it's ticket\n> successfully via the keytab file:\n\nSo, from Windows clients that don't have MIT KfW installed, you're able\nto authenticate against PG 12 on Ubuntu using Kerberos, right..? With\nPG built using SSPI on the client side, I'm guessing?\n\nKerberos uses reverse DNS to try to check what hostname to use when\nrequesting a ticket, I wonder if what you're seeing here is a delay due\nto there not being reverse DNS functional in the environment, perhaps..?\n\n> C:\\pg>\"c:\\Program Files\\MIT\\Kerberos\\bin\\klist.exe\"\n> Ticket cache: API:Initial default ccache\n> Default principal: dpage@PGADMIN.ORG\n> \n> Valid starting Expires Service principal\n> 09/02/20 15:06:49 09/03/20 01:06:49 krbtgt/PGADMIN.ORG@PGADMIN.ORG\n> renew until 09/03/20 15:06:31\n> 09/02/20 15:07:06 09/03/20 01:06:49 postgres/win-ilt1arj8a9c@\n> renew until 09/03/20 15:06:31\n> 09/02/20 15:07:06 09/03/20 01:06:49 postgres/win-ilt1arj8a9c@PGADMIN.ORG\n> renew until 09/03/20 15:06:31\n> \n> However, If I try to login using host + gss in the pg_hba.conf file, I then\n> get:\n> \n> C:\\pg>bin\\psql postgres\n> psql: error: could not connect to server: SSPI continuation error: No\n> credentials are available in the security package\n> (8009030e)\n\nThis is with PG compiled with GSS on the client side and using MIT KfW?\n\nThis particular error from SSPI seems to possibly be coming from the\nconstrained delegation system. While not directly about this issue,\nMicrosoft has some documentation about configuring constrained\ndelegation (and how to turn it off) here:\n\nhttps://docs.microsoft.com/en-us/windows-server/virtualization/hyper-v/deploy/Set-up-hosts-for-live-migration-without-Failover-Clustering\n\nNow, we aren't actually delegating credentials here, so it seems a bit\nodd for it to be complaining about that, but perhaps it's throwing this\nerror because the MIT KfW library has no clue about constrained\ndelegation and therefore wouldn't be trying to enforce it.\n\n> If I try to use hostgssenc + gss, it looks like it's not even trying to\n> encrypt:\n> \n> C:\\pg>bin\\psql postgres\n> psql: error: could not connect to server: FATAL: no pg_hba.conf entry for\n> host \"::1\", user \"dpage\", database \"postgres\", SSL off\n> \n> Any ideas?\n\nIf it's not trying then I would be suspicious that the\ngss_acquire_creds() call is saying that there isn't a credential cache,\nthough that would be a bit odd given that klist seems to be working.\n\nWould certainly be interesting to see if 1.18.2 changes anything in this\nregard.\n\nThanks,\n\nStephen", "msg_date": "Wed, 2 Sep 2020 14:08:38 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Kerberos support broken on MSVC builds for Windows x64?" }, { "msg_contents": "Hi\n\nOn Wed, Sep 2, 2020 at 7:08 PM Stephen Frost <sfrost@snowman.net> wrote:\n\n> Greetings,\n>\n> * Dave Page (dpage@pgadmin.org) wrote:\n> > On Wed, Sep 2, 2020 at 9:05 AM Dave Page <dpage@pgadmin.org> wrote:\n> > >> Yes, that'd be in the GSSENC code, which I hadn't been expecting to be\n> > >> used under Windows.\n> >\n> > Here's a patch to make it build successfully (against head). I believe\n> the\n> > changes to Solution.pm should be back patched all the way, and the rest\n> to\n> > 12.\n>\n> Looks about right.. I might pull out the code from both places that are\n> setting that variable into a dedicated function to be used from both\n> though.\n>\n> > Testing however, has been more problematic - I suspect at least partly\n> > because of my Kerberos newbie-ness. I have a test server in an Ubuntu VM,\n> > which I've used quite successfully to authenticate against another VM\n> > running PG 12 on Ubuntu, from both Ubuntu and Windows clients. Using\n> that,\n> > but with a Windows client running MIT Kerberos I find that getting a\n> ticket\n> > takes a good 30 seconds or so. Postgres also seems to get it's ticket\n> > successfully via the keytab file:\n>\n> So, from Windows clients that don't have MIT KfW installed, you're able\n> to authenticate against PG 12 on Ubuntu using Kerberos, right..? With\n> PG built using SSPI on the client side, I'm guessing?\n>\n\nYes, with the workstation configured to authenticate windows login with\nKerberos (e.g.\nhttps://www.garyhawkins.me.uk/non-domain-mit-kerberos-logins-on-windows-10/)\n\n\n>\n> Kerberos uses reverse DNS to try to check what hostname to use when\n> requesting a ticket, I wonder if what you're seeing here is a delay due\n> to there not being reverse DNS functional in the environment, perhaps..?\n>\n\nAhh, probably. I'm just using host files on these VMs, but I'll bet I\nforgot to add the client to the kdc's file. Will try that tomorrow.\n\n\n>\n> > C:\\pg>\"c:\\Program Files\\MIT\\Kerberos\\bin\\klist.exe\"\n> > Ticket cache: API:Initial default ccache\n> > Default principal: dpage@PGADMIN.ORG\n> >\n> > Valid starting Expires Service principal\n> > 09/02/20 15:06:49 09/03/20 01:06:49 krbtgt/PGADMIN.ORG@PGADMIN.ORG\n> > renew until 09/03/20 15:06:31\n> > 09/02/20 15:07:06 09/03/20 01:06:49 postgres/win-ilt1arj8a9c@\n> > renew until 09/03/20 15:06:31\n> > 09/02/20 15:07:06 09/03/20 01:06:49 postgres/\n> win-ilt1arj8a9c@PGADMIN.ORG\n> > renew until 09/03/20 15:06:31\n> >\n> > However, If I try to login using host + gss in the pg_hba.conf file, I\n> then\n> > get:\n> >\n> > C:\\pg>bin\\psql postgres\n> > psql: error: could not connect to server: SSPI continuation error: No\n> > credentials are available in the security package\n> > (8009030e)\n>\n> This is with PG compiled with GSS on the client side and using MIT KfW?\n>\n\nYes.\n\n\n>\n> This particular error from SSPI seems to possibly be coming from the\n> constrained delegation system. While not directly about this issue,\n> Microsoft has some documentation about configuring constrained\n> delegation (and how to turn it off) here:\n>\n>\n> https://docs.microsoft.com/en-us/windows-server/virtualization/hyper-v/deploy/Set-up-hosts-for-live-migration-without-Failover-Clustering\n>\n> Now, we aren't actually delegating credentials here, so it seems a bit\n> odd for it to be complaining about that, but perhaps it's throwing this\n> error because the MIT KfW library has no clue about constrained\n> delegation and therefore wouldn't be trying to enforce it.\n>\n\nOK, I'll look into that.\n\n\n>\n> > If I try to use hostgssenc + gss, it looks like it's not even trying to\n> > encrypt:\n> >\n> > C:\\pg>bin\\psql postgres\n> > psql: error: could not connect to server: FATAL: no pg_hba.conf entry\n> for\n> > host \"::1\", user \"dpage\", database \"postgres\", SSL off\n> >\n> > Any ideas?\n>\n> If it's not trying then I would be suspicious that the\n> gss_acquire_creds() call is saying that there isn't a credential cache,\n> though that would be a bit odd given that klist seems to be working.\n>\n> Would certainly be interesting to see if 1.18.2 changes anything in this\n> regard.\n>\n\nI'll let you know how that goes. Thanks for the tips!\n\n-- \nDave Page\nBlog: http://pgsnake.blogspot.com\nTwitter: @pgsnake\n\nEDB: http://www.enterprisedb.com\n\nHiOn Wed, Sep 2, 2020 at 7:08 PM Stephen Frost <sfrost@snowman.net> wrote:Greetings,\n\n* Dave Page (dpage@pgadmin.org) wrote:\n> On Wed, Sep 2, 2020 at 9:05 AM Dave Page <dpage@pgadmin.org> wrote:\n> >> Yes, that'd be in the GSSENC code, which I hadn't been expecting to be\n> >> used under Windows.\n>\n> Here's a patch to make it build successfully (against head). I believe the\n> changes to Solution.pm should be back patched all the way, and the rest to\n> 12.\n\nLooks about right..  I might pull out the code from both places that are\nsetting that variable into a dedicated function to be used from both\nthough.\n\n> Testing however, has been more problematic - I suspect at least partly\n> because of my Kerberos newbie-ness. I have a test server in an Ubuntu VM,\n> which I've used quite successfully to authenticate against another VM\n> running PG 12  on Ubuntu, from both Ubuntu and Windows clients. Using that,\n> but with a Windows client running MIT Kerberos I find that getting a ticket\n> takes a good 30 seconds or so. Postgres also seems to get it's ticket\n> successfully via the keytab file:\n\nSo, from Windows clients that don't have MIT KfW installed, you're able\nto authenticate against PG 12 on Ubuntu using Kerberos, right..?  With\nPG built using SSPI on the client side, I'm guessing?Yes, with the workstation configured to authenticate windows login with Kerberos (e.g. https://www.garyhawkins.me.uk/non-domain-mit-kerberos-logins-on-windows-10/) \n\nKerberos uses reverse DNS to try to check what hostname to use when\nrequesting a ticket, I wonder if what you're seeing here is a delay due\nto there not being reverse DNS functional in the environment, perhaps..?Ahh, probably. I'm just using host files on these VMs, but I'll bet I forgot to add the client to the kdc's file. Will try that tomorrow. \n\n> C:\\pg>\"c:\\Program Files\\MIT\\Kerberos\\bin\\klist.exe\"\n> Ticket cache: API:Initial default ccache\n> Default principal: dpage@PGADMIN.ORG\n> \n> Valid starting     Expires            Service principal\n> 09/02/20 15:06:49  09/03/20 01:06:49  krbtgt/PGADMIN.ORG@PGADMIN.ORG\n>         renew until 09/03/20 15:06:31\n> 09/02/20 15:07:06  09/03/20 01:06:49  postgres/win-ilt1arj8a9c@\n>         renew until 09/03/20 15:06:31\n> 09/02/20 15:07:06  09/03/20 01:06:49  postgres/win-ilt1arj8a9c@PGADMIN.ORG\n>         renew until 09/03/20 15:06:31\n> \n> However, If I try to login using host + gss in the pg_hba.conf file, I then\n> get:\n> \n> C:\\pg>bin\\psql postgres\n> psql: error: could not connect to server: SSPI continuation error: No\n> credentials are available in the security package\n>  (8009030e)\n\nThis is with PG compiled with GSS on the client side and using MIT KfW?Yes. \n\nThis particular error from SSPI seems to possibly be coming from the\nconstrained delegation system.  While not directly about this issue,\nMicrosoft has some documentation about configuring constrained\ndelegation (and how to turn it off) here:\n\nhttps://docs.microsoft.com/en-us/windows-server/virtualization/hyper-v/deploy/Set-up-hosts-for-live-migration-without-Failover-Clustering\n\nNow, we aren't actually delegating credentials here, so it seems a bit\nodd for it to be complaining about that, but perhaps it's throwing this\nerror because the MIT KfW library has no clue about constrained\ndelegation and therefore wouldn't be trying to enforce it.OK, I'll look into that. \n\n> If I try to use hostgssenc + gss, it looks like it's not even trying to\n> encrypt:\n> \n> C:\\pg>bin\\psql postgres\n> psql: error: could not connect to server: FATAL:  no pg_hba.conf entry for\n> host \"::1\", user \"dpage\", database \"postgres\", SSL off\n> \n> Any ideas?\n\nIf it's not trying then I would be suspicious that the\ngss_acquire_creds() call is saying that there isn't a credential cache,\nthough that would be a bit odd given that klist seems to be working.\n\nWould certainly be interesting to see if 1.18.2 changes anything in this\nregard.I'll let you know how that goes. Thanks for the tips! -- Dave PageBlog: http://pgsnake.blogspot.comTwitter: @pgsnakeEDB: http://www.enterprisedb.com", "msg_date": "Wed, 2 Sep 2020 19:17:31 +0100", "msg_from": "Dave Page <dpage@pgadmin.org>", "msg_from_op": true, "msg_subject": "Re: Kerberos support broken on MSVC builds for Windows x64?" }, { "msg_contents": "On Wed, Sep 2, 2020 at 5:21 PM Dave Page <dpage@pgadmin.org> wrote:\n\n>\n>\n> On Wed, Sep 2, 2020 at 2:47 PM Stephen Frost <sfrost@snowman.net> wrote:\n>\n>> Greetings,\n>>\n>> * Dave Page (dpage@pgadmin.org) wrote:\n>> > On Tue, Sep 1, 2020 at 5:29 PM Stephen Frost <sfrost@snowman.net>\n>> wrote:\n>> > > * Dave Page (dpage@pgadmin.org) wrote:\n>> > > > Attached is a patch against 12.4 for the build system in case anyone\n>> > > wants\n>> > > > to play (I'll do it properly against the head branch later). I'm\n>> guessing\n>> > > > this will work for < 12, as with 12 I'm now getting the following\n>> which\n>> > > > looks like it's related to GSS encryption:\n>> > > >\n>> > > > \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgsql.sln\" (default\n>> target)\n>> > > (1) ->\n>> > > > \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgcrypto.vcxproj\" (default\n>> > > > target) (2) ->\n>> > > > \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj\" (default\n>> > > > target) (3) ->\n>> > > > (Link target) ->\n>> > > > be-secure-gssapi.obj : error LNK2019: unresolved external symbol\n>> setenv\n>> > > > referenced in function secure_open_gssapi\n>> > > > [C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj]\n>> > > > .\\Release\\postgres\\postgres.exe : fatal error LNK1120: 1\n>> unresolved\n>> > > > externals\n>> [C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj]\n>> > > >\n>> > > > I'll dig into that some more.\n>> > >\n>> > > Yes, that'd be in the GSSENC code, which I hadn't been expecting to be\n>> > > used under Windows. If you're successful, I don't have any issue\n>> > > helping to make that work, though I'm curious if you're trying to\n>> build\n>> > > with MIT KfW (which is rather ancient these days, being based on krb5\n>> > > 1.13 and not updated since..) or with a more current release...?\n>> >\n>> > I'm currently using the KFW 4.1 build from MIT. I've tried building it\n>> > myself but it requires a very old toolchain (which defeated the point of\n>> > what I was trying to do at the time).\n>>\n>> > I haven't yet looked to see if the source for krb5-1.8.2 will build or\n>> even\n>> > has the right bits in it for Windows - as I'm sure you know MIT seem to\n>> > maintain an entirely different version for Windows for which I assume\n>> > there's a reason.\n>>\n>> I'm a bit confused as to why you'd consider trying 1.8.2- did you mean\n>> 1.18.2 there, perhaps..?\n>\n>\n> Yes, typo.\n>\n>\n>> That's what I would think to try, since, as I\n>> understand it from following the Kerberos Dev list (which is pretty\n>> responsive...) has been updated to work with newer Windows build\n>> toolchains.\n>>\n>\n> OK, will try to do that tomorrow.\n>\n> Thanks!\n>\n\nOK, so 1.18.2 builds OK. It's a bit of a faff, but nothing major. It seems\nto work fine as a standalone set of tools.\n\nOf course, they've changed the installation paths again - they've dropped\nthe i386 and amd64 parts from the library path :-/\n\nSo having rebuilt PostgreSQL against that, I'm now in the situation where\nthe server never even attempts to get a ticket as far as I can see, and\npsql just crashes with nothing more than a useless error in the event log:\n\nFaulting application name: psql.exe, version: 14.0.0.20246, time stamp:\n0x5f50e477\nFaulting module name: unknown, version: 0.0.0.0, time stamp: 0x00000000\nException code: 0xc0000005\nFault offset: 0x0000000000000000\nFaulting process id: 0xd10\nFaulting application start time: 0x01d681f189a17360\nFaulting application path: C:\\pg\\bin\\psql.exe\nFaulting module path: unknown\nReport Id: eb68d787-1c82-420d-8878-bc0648932a5d\nFaulting package full name:\nFaulting package-relative application ID:\n\nSo I'm going to have to break out the debugger, though I suspect this may\nrequire more effort than I have time for right now.\n\n\n-- \nDave Page\nBlog: http://pgsnake.blogspot.com\nTwitter: @pgsnake\n\nEDB: http://www.enterprisedb.com\n\nOn Wed, Sep 2, 2020 at 5:21 PM Dave Page <dpage@pgadmin.org> wrote:On Wed, Sep 2, 2020 at 2:47 PM Stephen Frost <sfrost@snowman.net> wrote:Greetings,\n\n* Dave Page (dpage@pgadmin.org) wrote:\n> On Tue, Sep 1, 2020 at 5:29 PM Stephen Frost <sfrost@snowman.net> wrote:\n> > * Dave Page (dpage@pgadmin.org) wrote:\n> > > Attached is a patch against 12.4 for the build system in case anyone\n> > wants\n> > > to play (I'll do it properly against the head branch later). I'm guessing\n> > > this will work for < 12, as with 12 I'm now getting the following which\n> > > looks like it's related to GSS encryption:\n> > >\n> > > \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgsql.sln\" (default target)\n> > (1) ->\n> > > \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\pgcrypto.vcxproj\" (default\n> > > target) (2) ->\n> > > \"C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj\" (default\n> > > target) (3) ->\n> > > (Link target) ->\n> > >   be-secure-gssapi.obj : error LNK2019: unresolved external symbol setenv\n> > > referenced in function secure_open_gssapi\n> > > [C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj]\n> > >   .\\Release\\postgres\\postgres.exe : fatal error LNK1120: 1 unresolved\n> > > externals [C:\\Users\\dpage\\Downloads\\postgresql-12.4\\postgres.vcxproj]\n> > >\n> > > I'll dig into that some more.\n> >\n> > Yes, that'd be in the GSSENC code, which I hadn't been expecting to be\n> > used under Windows.  If you're successful, I don't have any issue\n> > helping to make that work, though I'm curious if you're trying to build\n> > with MIT KfW (which is rather ancient these days, being based on krb5\n> > 1.13 and not updated since..) or with a more current release...?\n> \n> I'm currently using the KFW 4.1 build from MIT. I've tried building it\n> myself but it requires a very old toolchain (which defeated the point of\n> what I was trying to do at the time).\n\n> I haven't yet looked to see if the source for krb5-1.8.2 will build or even\n> has the right bits in it for Windows - as I'm sure you know MIT seem to\n> maintain an entirely different version for Windows for which I assume\n> there's a reason.\n\nI'm a bit confused as to why you'd consider trying 1.8.2- did you mean\n1.18.2 there, perhaps..?  Yes, typo. That's what I would think to try, since, as I\nunderstand it from following the Kerberos Dev list (which is pretty\nresponsive...) has been updated to work with newer Windows build\ntoolchains.OK, will try to do that tomorrow.Thanks!OK, so 1.18.2 builds OK. It's a bit of a faff, but nothing major. It seems to work fine as a standalone set of tools.Of course, they've changed the installation paths again - they've dropped the i386 and amd64 parts from the library path :-/So having rebuilt PostgreSQL against that, I'm now in the situation where the server never even attempts to get a ticket as far as I can see, and psql just crashes with nothing more than a useless error in the event log:Faulting application name: psql.exe, version: 14.0.0.20246, time stamp: 0x5f50e477Faulting module name: unknown, version: 0.0.0.0, time stamp: 0x00000000Exception code: 0xc0000005Fault offset: 0x0000000000000000Faulting process id: 0xd10Faulting application start time: 0x01d681f189a17360Faulting application path: C:\\pg\\bin\\psql.exeFaulting module path: unknownReport Id: eb68d787-1c82-420d-8878-bc0648932a5dFaulting package full name: Faulting package-relative application ID: So I'm going to have to break out the debugger, though I suspect this may require more effort than I have time for right now.-- Dave PageBlog: http://pgsnake.blogspot.comTwitter: @pgsnakeEDB: http://www.enterprisedb.com", "msg_date": "Thu, 3 Sep 2020 16:15:03 +0100", "msg_from": "Dave Page <dpage@pgadmin.org>", "msg_from_op": true, "msg_subject": "Re: Kerberos support broken on MSVC builds for Windows x64?" }, { "msg_contents": "On Thu, Sep 3, 2020 at 4:15 PM Dave Page <dpage@pgadmin.org> wrote:\n\n>\n> So having rebuilt PostgreSQL against that, I'm now in the situation where\n> the server never even attempts to get a ticket as far as I can see, and\n> psql just crashes with nothing more than a useless error in the event log:\n>\n> Faulting application name: psql.exe, version: 14.0.0.20246, time stamp:\n> 0x5f50e477\n> Faulting module name: unknown, version: 0.0.0.0, time stamp: 0x00000000\n> Exception code: 0xc0000005\n> Fault offset: 0x0000000000000000\n> Faulting process id: 0xd10\n> Faulting application start time: 0x01d681f189a17360\n> Faulting application path: C:\\pg\\bin\\psql.exe\n> Faulting module path: unknown\n> Report Id: eb68d787-1c82-420d-8878-bc0648932a5d\n> Faulting package full name:\n> Faulting package-relative application ID:\n>\n> So I'm going to have to break out the debugger, though I suspect this may\n> require more effort than I have time for right now.\n>\n\nYeah, this is almost certainly well beyond what I have the time to figure\nout. Happy to do any testing etc. that may be needed, but I think this\nneeds someone familiar with the GSS API to take the lead.\n\nHere's what I got from psql in the debugger:\n\nException thrown at 0x0000000000000000 in psql.exe: 0xC0000005: Access\nviolation executing location 0x0000000000000000. occurred\n\n0000000000000000()\nkrb5_64.dll!0000000051942807()\nkrb5_64.dll!000000005194214b()\nkrb5_64.dll!0000000051980611()\nkrb5_64.dll!00000000519766cb()\nkrb5_64.dll!00000000519670ff()\ngssapi64.dll!0000000051bb1839()\ngssapi64.dll!0000000051bb48e4()\ngssapi64.dll!0000000051bb4575()\ngssapi64.dll!0000000051b993df()\nlibpq.dll!pqsecure_open_gss(pg_conn * conn) Line 632\nat\nc:\\users\\dpage\\downloads\\postgresql\\src\\interfaces\\libpq\\fe-secure-gssapi.c(632)\nlibpq.dll!PQconnectPoll(pg_conn * conn) Line 3173\nat\nc:\\users\\dpage\\downloads\\postgresql\\src\\interfaces\\libpq\\fe-connect.c(3173)\nlibpq.dll!connectDBComplete(pg_conn * conn) Line 2187\nat\nc:\\users\\dpage\\downloads\\postgresql\\src\\interfaces\\libpq\\fe-connect.c(2187)\nlibpq.dll!PQconnectdbParams(const char * const * keywords, const char *\nconst * values, int expand_dbname) Line 655\nat\nc:\\users\\dpage\\downloads\\postgresql\\src\\interfaces\\libpq\\fe-connect.c(655)\npsql.exe!main(int argc, char * * argv) Line 266\nat c:\\users\\dpage\\downloads\\postgresql\\src\\bin\\psql\\startup.c(266)\n[External Code]\n\n-- \nDave Page\nBlog: http://pgsnake.blogspot.com\nTwitter: @pgsnake\n\nEDB: http://www.enterprisedb.com\n\nOn Thu, Sep 3, 2020 at 4:15 PM Dave Page <dpage@pgadmin.org> wrote:So having rebuilt PostgreSQL against that, I'm now in the situation where the server never even attempts to get a ticket as far as I can see, and psql just crashes with nothing more than a useless error in the event log:Faulting application name: psql.exe, version: 14.0.0.20246, time stamp: 0x5f50e477Faulting module name: unknown, version: 0.0.0.0, time stamp: 0x00000000Exception code: 0xc0000005Fault offset: 0x0000000000000000Faulting process id: 0xd10Faulting application start time: 0x01d681f189a17360Faulting application path: C:\\pg\\bin\\psql.exeFaulting module path: unknownReport Id: eb68d787-1c82-420d-8878-bc0648932a5dFaulting package full name: Faulting package-relative application ID: So I'm going to have to break out the debugger, though I suspect this may require more effort than I have time for right now.Yeah, this is almost certainly well beyond what I have the time to figure out. Happy to do any testing etc. that may be needed, but I think this needs someone familiar with the GSS API to take the lead.Here's what I got from psql in the debugger:Exception thrown at 0x0000000000000000 in psql.exe: 0xC0000005: Access violation executing location 0x0000000000000000. occurred0000000000000000()krb5_64.dll!0000000051942807()krb5_64.dll!000000005194214b()krb5_64.dll!0000000051980611()krb5_64.dll!00000000519766cb()krb5_64.dll!00000000519670ff()gssapi64.dll!0000000051bb1839()gssapi64.dll!0000000051bb48e4()gssapi64.dll!0000000051bb4575()gssapi64.dll!0000000051b993df()libpq.dll!pqsecure_open_gss(pg_conn * conn) Line 632\tat c:\\users\\dpage\\downloads\\postgresql\\src\\interfaces\\libpq\\fe-secure-gssapi.c(632)libpq.dll!PQconnectPoll(pg_conn * conn) Line 3173\tat c:\\users\\dpage\\downloads\\postgresql\\src\\interfaces\\libpq\\fe-connect.c(3173)libpq.dll!connectDBComplete(pg_conn * conn) Line 2187\tat c:\\users\\dpage\\downloads\\postgresql\\src\\interfaces\\libpq\\fe-connect.c(2187)libpq.dll!PQconnectdbParams(const char * const * keywords, const char * const * values, int expand_dbname) Line 655\tat c:\\users\\dpage\\downloads\\postgresql\\src\\interfaces\\libpq\\fe-connect.c(655)psql.exe!main(int argc, char * * argv) Line 266\tat c:\\users\\dpage\\downloads\\postgresql\\src\\bin\\psql\\startup.c(266)[External Code] -- Dave PageBlog: http://pgsnake.blogspot.comTwitter: @pgsnakeEDB: http://www.enterprisedb.com", "msg_date": "Thu, 3 Sep 2020 16:54:37 +0100", "msg_from": "Dave Page <dpage@pgadmin.org>", "msg_from_op": true, "msg_subject": "Re: Kerberos support broken on MSVC builds for Windows x64?" } ]
[ { "msg_contents": "Hi,\n\nPostgres's describe-config option prints reset_val for int & real\nconfiguration parameters which is not useful as it is not updated.\nPrinting boot_val is better in this case. reset_val is updated with\nboot_val while the server is getting started but in case of postgres\n--describe-config this value is not updated. I felt printing boot_val\nis more appropriate in this case. Attached patch for the same.\nThoughts?\n\nRegards,\nVignesh\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Wed, 2 Sep 2020 10:35:23 +0530", "msg_from": "vignesh C <vignesh21@gmail.com>", "msg_from_op": true, "msg_subject": "describe-config issue" }, { "msg_contents": "vignesh C <vignesh21@gmail.com> writes:\n> Postgres's describe-config option prints reset_val for int & real\n> configuration parameters which is not useful as it is not updated.\n\nUh, what?\n\n> Printing boot_val is better in this case.\n\nPlease defend that claim. Otherwise this seems like a pretty\nrandom change.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 02 Sep 2020 10:36:23 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: describe-config issue" }, { "msg_contents": "On Wed, Sep 2, 2020 at 8:06 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Please defend that claim. Otherwise this seems like a pretty\n> random change.\n\nI had seen that there is discrepancy in postgres --describe-config & the\nvalue displayed from pg_settings like in the below case:\npostgres=# select name,min_val, max_val, boot_val,reset_val from\npg_settings where name = 'checkpoint_timeout';\n name | min_val | max_val | *boot_val | reset_val*\n--------------------+---------+---------+----------+-----------\n checkpoint_timeout | 30 | 86400 | *300 | 300*\n(1 row)\n\n[vignesh@localhost bin]$ ./postgres --describe-config | grep\ncheckpoint_timeout\ncheckpoint_timeout sighup Write-Ahead Log / Checkpoints INTEGER *0 *30\n86400 Sets the maximum time between automatic WAL checkpoints.\n\nIn the case of pg_settings we display 300 for boot_val/reset_val whereas in\nthe case of describe-config we display 0, shouldn't it be 300 here?\nThoughts?\n\n Regards,\nVignesh\nEnterpriseDB: http://www.enterprisedb.com\n\nOn Wed, Sep 2, 2020 at 8:06 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:> Please defend that claim.  Otherwise this seems like a pretty> random change.I had seen that there is discrepancy in postgres --describe-config & the value displayed from pg_settings like in the below case:postgres=# select name,min_val, max_val, boot_val,reset_val from pg_settings where name = 'checkpoint_timeout';        name        | min_val | max_val | boot_val | reset_val --------------------+---------+---------+----------+----------- checkpoint_timeout | 30      | 86400   | 300      | 300(1 row)[vignesh@localhost bin]$ ./postgres --describe-config | grep checkpoint_timeoutcheckpoint_timeout sighup Write-Ahead Log / Checkpoints INTEGER 0 30 86400 Sets the maximum time between automatic WAL checkpoints.In the case of pg_settings we display 300 for boot_val/reset_val whereas in the case of describe-config we display 0, shouldn't it be 300 here?Thoughts? Regards,VigneshEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Thu, 3 Sep 2020 07:22:43 +0530", "msg_from": "vignesh C <vignesh21@gmail.com>", "msg_from_op": true, "msg_subject": "Re: describe-config issue" } ]
[ { "msg_contents": "Hello hackers,\n\nYou don't need to call stat() just to find out if a dirent is a file\nor directory, most of the time. Please see attached.", "msg_date": "Wed, 2 Sep 2020 17:18:38 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "A micro-optimisation for walkdir()" }, { "msg_contents": "Thomas Munro <thomas.munro@gmail.com> writes:\n> You don't need to call stat() just to find out if a dirent is a file\n> or directory, most of the time. Please see attached.\n\nHm. If we do this, I can see wanting to apply the knowledge in more\nplaces than walkdir(). Is it possible to extract out the nonstandard\nbits into a reusable subroutine? I'm envisioning an API more or less\nlike\n\n extern enum PGFileType identify_file_type(const char *path,\n const struct dirent *de,\n bool look_thru_symlinks);\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 02 Sep 2020 10:34:58 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "On Wed, Sep 2, 2020 at 4:35 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Thomas Munro <thomas.munro@gmail.com> writes:\n> > You don't need to call stat() just to find out if a dirent is a file\n> > or directory, most of the time. Please see attached.\n>\n> Hm. If we do this, I can see wanting to apply the knowledge in more\n> places than walkdir().\n>\n\nWin32 could also benefit from this micro-optimisation if we expanded the\ndirent port to include d_type. Please find attached a patch that does so.\n\nRegards,\n\nJuan José Santamaría Flecha", "msg_date": "Wed, 2 Sep 2020 17:51:27 +0200", "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: A micro-optimisation for walkdir()" }, { "msg_contents": "On Thu, Sep 3, 2020 at 3:52 AM Juan José Santamaría Flecha\n<juanjo.santamaria@gmail.com> wrote:\n> On Wed, Sep 2, 2020 at 4:35 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> Thomas Munro <thomas.munro@gmail.com> writes:\n>> > You don't need to call stat() just to find out if a dirent is a file\n>> > or directory, most of the time. Please see attached.\n>>\n>> Hm. If we do this, I can see wanting to apply the knowledge in more\n>> places than walkdir().\n\nGood idea. Here's a new version that defines a new function\nget_dirent_type() in src/common/file_utils_febe.c and uses it for both\nfrontend and backend walkdir().\n\n> Win32 could also benefit from this micro-optimisation if we expanded the dirent port to include d_type. Please find attached a patch that does so.\n\nIs GetFileAttributes() actually faster than stat()? Oh, I see that\nour pgwin32_safestat() makes extra system calls. Huh. Ok then.\nThanks!", "msg_date": "Thu, 3 Sep 2020 17:08:48 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "Thomas Munro <thomas.munro@gmail.com> writes:\n>> On Wed, Sep 2, 2020 at 4:35 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>>> Hm. If we do this, I can see wanting to apply the knowledge in more\n>>> places than walkdir().\n\n> Good idea. Here's a new version that defines a new function\n> get_dirent_type() in src/common/file_utils_febe.c and uses it for both\n> frontend and backend walkdir().\n\nQuick thoughts on this patch:\n\n* The API spec for get_dirent_type() needs to say that errno is\nmeaningful when the return value is PGFILETYPE_ERROR. That's\nsomething that would not be hard to break, so not documenting\nthe point at all doesn't seem great. More generally, I don't\nespecially like having the callers know that the errno is from\nstat() rather than something else.\n\n* I don't quite like the calling code you have that covers some\nreturn values and then has a default: case without any comment.\nIt's not really obvious that the default: case is expected to be\nhit in non-error situations, especially when there is a separate\nswitch path for errors. I can't find fault with the code as such,\nbut I think it'd be good to have a comment there. Maybe along\nthe lines of \"Ignore file types other than regular files and\ndirectories\".\n\nBoth of these concerns would abate if we had get_dirent_type()\njust throw an error itself when stat() fails, thereby removing the\nPGFILETYPE_ERROR result code. I'm not 100% sold either way on\nthat, but it's something to think about. Is there ever going\nto be a reason for the caller to ignore an error?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 03 Sep 2020 01:36:16 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "On Thu, Sep 3, 2020 at 5:36 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> [request for better comments]\n\nAck.\n\n> Both of these concerns would abate if we had get_dirent_type()\n> just throw an error itself when stat() fails, thereby removing the\n> PGFILETYPE_ERROR result code. I'm not 100% sold either way on\n> that, but it's something to think about. Is there ever going\n> to be a reason for the caller to ignore an error?\n\nHmm. Well I had it like that in an earlier version, but then I\ncouldn't figure out the right way to write code that would work in\nboth frontend and backend code, without writing two copies in two\ntranslation units, or putting the whole thing in a header. What\napproach do you prefer?\n\n\n", "msg_date": "Thu, 3 Sep 2020 18:38:07 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "Thomas Munro <thomas.munro@gmail.com> writes:\n> On Thu, Sep 3, 2020 at 5:36 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> Both of these concerns would abate if we had get_dirent_type()\n>> just throw an error itself when stat() fails, thereby removing the\n>> PGFILETYPE_ERROR result code. I'm not 100% sold either way on\n>> that, but it's something to think about. Is there ever going\n>> to be a reason for the caller to ignore an error?\n\n> Hmm. Well I had it like that in an earlier version, but then I\n> couldn't figure out the right way to write code that would work in\n> both frontend and backend code, without writing two copies in two\n> translation units, or putting the whole thing in a header. What\n> approach do you prefer?\n\nWell, there are plenty of places in src/port/ where we do things like\n\n#ifndef FRONTEND\n ereport(ERROR,\n (errcode_for_file_access(),\n errmsg(\"could not get junction for \\\"%s\\\": %s\",\n path, msg)));\n#else\n fprintf(stderr, _(\"could not get junction for \\\"%s\\\": %s\\n\"),\n path, msg);\n#endif\n\nI don't see a compelling reason why this function couldn't report\nstat() failures similarly, especially if we're just going to have\nthe callers do exactly the same thing as that anyway.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 03 Sep 2020 11:31:40 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "On Fri, Sep 4, 2020 at 3:31 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Thomas Munro <thomas.munro@gmail.com> writes:\n> > Hmm. Well I had it like that in an earlier version, but then I\n> > couldn't figure out the right way to write code that would work in\n> > both frontend and backend code, without writing two copies in two\n> > translation units, or putting the whole thing in a header. What\n> > approach do you prefer?\n>\n> Well, there are plenty of places in src/port/ where we do things like\n>\n> #ifndef FRONTEND\n> ereport(ERROR,\n> (errcode_for_file_access(),\n> errmsg(\"could not get junction for \\\"%s\\\": %s\",\n> path, msg)));\n> #else\n> fprintf(stderr, _(\"could not get junction for \\\"%s\\\": %s\\n\"),\n> path, msg);\n> #endif\n>\n> I don't see a compelling reason why this function couldn't report\n> stat() failures similarly, especially if we're just going to have\n> the callers do exactly the same thing as that anyway.\n\nOk, so the main weird thing is that you finish up having to pass in an\nelevel, but that has different meanings in FE and BE code. Note that\nyou still need a PGFILE_ERROR return value, because we don't log\nmessages at a level that exits non-locally (and that concept doesn't\neven exist for FE logging).", "msg_date": "Fri, 4 Sep 2020 11:58:21 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "On 2020-Sep-04, Thomas Munro wrote:\n\n> @@ -10,6 +10,7 @@ struct dirent\n> {\n> \tlong\t\td_ino;\n> \tunsigned short d_reclen;\n> +\tunsigned char d_type;\n> \tunsigned short d_namlen;\n> \tchar\t\td_name[MAX_PATH];\n> };\n> @@ -20,4 +21,26 @@ DIR\t\t *opendir(const char *);\n> struct dirent *readdir(DIR *);\n> int\t\t\tclosedir(DIR *);\n> \n> +/* File types for 'd_type'. */\n> +enum\n> + {\n> +\tDT_UNKNOWN = 0,\n> +# define DT_UNKNOWN\t\tDT_UNKNOWN\n\nUhm ... what do these #defines do? They look a bit funny.\n\nWould it make sense to give this enum a name, and then use that name in\nstruct dirent's definition, instead of unsigned char?\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 4 Sep 2020 15:37:24 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "On Fri, Sep 4, 2020 at 9:37 PM Alvaro Herrera <alvherre@2ndquadrant.com>\nwrote:\n\n> On 2020-Sep-04, Thomas Munro wrote:\n>\n> > @@ -10,6 +10,7 @@ struct dirent\n> > {\n> > long d_ino;\n> > unsigned short d_reclen;\n> > + unsigned char d_type;\n> > unsigned short d_namlen;\n> > char d_name[MAX_PATH];\n> > };\n> > @@ -20,4 +21,26 @@ DIR *opendir(const char *);\n> > struct dirent *readdir(DIR *);\n> > int closedir(DIR *);\n> >\n> > +/* File types for 'd_type'. */\n> > +enum\n> > + {\n> > + DT_UNKNOWN = 0,\n> > +# define DT_UNKNOWN DT_UNKNOWN\n>\n> Uhm ... what do these #defines do? They look a bit funny.\n>\n> Would it make sense to give this enum a name, and then use that name in\n> struct dirent's definition, instead of unsigned char?\n>\n\nThey mimic POSIX dirent.h. I would rather stick to that.\n\nRegards,\n\nJuan José Santamaría Flecha\n\nOn Fri, Sep 4, 2020 at 9:37 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:On 2020-Sep-04, Thomas Munro wrote:\n\n> @@ -10,6 +10,7 @@ struct dirent\n>  {\n>       long            d_ino;\n>       unsigned short d_reclen;\n> +     unsigned char d_type;\n>       unsigned short d_namlen;\n>       char            d_name[MAX_PATH];\n>  };\n> @@ -20,4 +21,26 @@ DIR                   *opendir(const char *);\n>  struct dirent *readdir(DIR *);\n>  int                  closedir(DIR *);\n>  \n> +/* File types for 'd_type'. */\n> +enum\n> +  {\n> +     DT_UNKNOWN = 0,\n> +# define DT_UNKNOWN          DT_UNKNOWN\n\nUhm ... what do these #defines do?  They look a bit funny.\n\nWould it make sense to give this enum a name, and then use that name in\nstruct dirent's definition, instead of unsigned char?They mimic POSIX dirent.h. I would rather stick to that.Regards,Juan José Santamaría Flecha", "msg_date": "Fri, 4 Sep 2020 22:03:38 +0200", "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: A micro-optimisation for walkdir()" }, { "msg_contents": "On 2020-Sep-04, Juan Jos� Santamar�a Flecha wrote:\n\n> On Fri, Sep 4, 2020 at 9:37 PM Alvaro Herrera <alvherre@2ndquadrant.com>\n> wrote:\n> \n> > On 2020-Sep-04, Thomas Munro wrote:\n\n> > >\n> > > +/* File types for 'd_type'. */\n> > > +enum\n> > > + {\n> > > + DT_UNKNOWN = 0,\n> > > +# define DT_UNKNOWN DT_UNKNOWN\n> >\n> > Uhm ... what do these #defines do? They look a bit funny.\n> >\n> > Would it make sense to give this enum a name, and then use that name in\n> > struct dirent's definition, instead of unsigned char?\n> \n> They mimic POSIX dirent.h. I would rather stick to that.\n\nAh ... they do?\n\nIf you remove the #define lines, what happens to your patch?\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 4 Sep 2020 16:28:49 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "On Fri, Sep 4, 2020 at 10:28 PM Alvaro Herrera <alvherre@2ndquadrant.com>\nwrote:\n\n> On 2020-Sep-04, Juan José Santamaría Flecha wrote:\n>\n> > On Fri, Sep 4, 2020 at 9:37 PM Alvaro Herrera <alvherre@2ndquadrant.com>\n> > wrote:\n> >\n> > > On 2020-Sep-04, Thomas Munro wrote:\n>\n> > > >\n> > > > +/* File types for 'd_type'. */\n> > > > +enum\n> > > > + {\n> > > > + DT_UNKNOWN = 0,\n> > > > +# define DT_UNKNOWN DT_UNKNOWN\n> > >\n> > > Uhm ... what do these #defines do? They look a bit funny.\n> > >\n> > > Would it make sense to give this enum a name, and then use that name in\n> > > struct dirent's definition, instead of unsigned char?\n> >\n> > They mimic POSIX dirent.h. I would rather stick to that.\n>\n> Ah ... they do?\n>\n> If you remove the #define lines, what happens to your patch?\n>\n\nIf will fail to detect that the patch makes the optimisation available for\nWIN32:\n\n+#if defined(DT_UNKNOWN) && defined(DT_REG) && defined(DT_DIR) &&\ndefined(DT_LNK)\n\nRegards,\n\nJuan José Santamaría Flecha\n\nOn Fri, Sep 4, 2020 at 10:28 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:On 2020-Sep-04, Juan José Santamaría Flecha wrote:\n\n> On Fri, Sep 4, 2020 at 9:37 PM Alvaro Herrera <alvherre@2ndquadrant.com>\n> wrote:\n> \n> > On 2020-Sep-04, Thomas Munro wrote:\n\n> > >\n> > > +/* File types for 'd_type'. */\n> > > +enum\n> > > +  {\n> > > +     DT_UNKNOWN = 0,\n> > > +# define DT_UNKNOWN          DT_UNKNOWN\n> >\n> > Uhm ... what do these #defines do?  They look a bit funny.\n> >\n> > Would it make sense to give this enum a name, and then use that name in\n> > struct dirent's definition, instead of unsigned char?\n> \n> They mimic POSIX dirent.h. I would rather stick to that.\n\nAh ... they do?\n\nIf you remove the #define lines, what happens to your patch?If will fail to detect that the patch makes the optimisation available for WIN32:+#if defined(DT_UNKNOWN) && defined(DT_REG) && defined(DT_DIR) && defined(DT_LNK)Regards,Juan José Santamaría Flecha", "msg_date": "Fri, 4 Sep 2020 22:34:17 +0200", "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: A micro-optimisation for walkdir()" }, { "msg_contents": "On 2020-Sep-04, Juan Jos� Santamar�a Flecha wrote:\n\n> If will fail to detect that the patch makes the optimisation available for\n> WIN32:\n> \n> +#if defined(DT_UNKNOWN) && defined(DT_REG) && defined(DT_DIR) &&\n> defined(DT_LNK)\n\nOh, I see. I suggest that it'd be better to change this line instead.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 4 Sep 2020 16:43:34 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> On 2020-Sep-04, Juan José Santamaría Flecha wrote:\n>> If will fail to detect that the patch makes the optimisation available for\n>> WIN32:\n>> \n>> +#if defined(DT_UNKNOWN) && defined(DT_REG) && defined(DT_DIR) &&\n>> defined(DT_LNK)\n\n> Oh, I see. I suggest that it'd be better to change this line instead.\n\nI think that it's standard to test for such symbols by seeing\nif they're defined as macros ... not least because that's the *only*\nway to test their existence in C.\n\nPersonally, what I'd do is lose the enum and just define the macros\nwith simple integer constant values.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 04 Sep 2020 17:39:34 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "Hi,\n\nOn 2020-09-02 17:51:27 +0200, Juan Jos� Santamar�a Flecha wrote:\n> Win32 could also benefit from this micro-optimisation if we expanded the\n> dirent port to include d_type. Please find attached a patch that does\n> so\n.\n> \t}\n> \tstrcpy(d->ret.d_name, fd.cFileName);\t/* Both strings are MAX_PATH long */\n> \td->ret.d_namlen = strlen(d->ret.d_name);\n> +\t/*\n> +\t * The only identifed types are: directory, regular file or symbolic link.\n> +\t * Errors are treated as a file type that could not be determined.\n> +\t */\n> +\tattrib = GetFileAttributes(d->ret.d_name);\n> +\tif (attrib == INVALID_FILE_ATTRIBUTES)\n> +\t\td->ret.d_type = DT_UNKNOWN;\n> +\telse if ((attrib & FILE_ATTRIBUTE_DIRECTORY) != 0)\n> +\t\td->ret.d_type = DT_DIR;\n> +\telse if ((attrib & FILE_ATTRIBUTE_REPARSE_POINT) != 0)\n> +\t\td->ret.d_type = DT_LNK;\n> +\telse\n> +\t\td->ret.d_type = DT_REG;\n> \n> \treturn &d->ret;\n> }\n\nIs this really an optimization? The benefit of Thomas' patch is that\nthat information sometimes already is there. But here you're doing a\nseparate lookup with GetFileAttributes()?\n\nWhat am I missing?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 4 Sep 2020 14:45:10 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "On 2020-Sep-04, Tom Lane wrote:\n\n> I think that it's standard to test for such symbols by seeing\n> if they're defined as macros ... not least because that's the *only*\n> way to test their existence in C.\n\nI guess since what we're doing is emulating standard readdir(), that\nmakes sense.\n\n> Personally, what I'd do is lose the enum and just define the macros\n> with simple integer constant values.\n\nWFM.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 4 Sep 2020 17:52:54 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "On Sat, Sep 5, 2020 at 9:45 AM Andres Freund <andres@anarazel.de> wrote:\n> On 2020-09-02 17:51:27 +0200, Juan José Santamaría Flecha wrote:\n> > + attrib = GetFileAttributes(d->ret.d_name);\n>\n> Is this really an optimization? The benefit of Thomas' patch is that\n> that information sometimes already is there. But here you're doing a\n> separate lookup with GetFileAttributes()?\n\nWell as discussed already, our stat() emulation on Windows does\nmultiple syscalls, so it's a slight improvement. However, it looks\nlike we might be missing a further opportunity here... Doesn't\nWindows already give us the flags we need in the dwFileAttributes\nmember of the WIN32_FIND_DATA object that the Find{First,Next}File()\nfunctions populate?\n\n\n", "msg_date": "Sat, 5 Sep 2020 11:15:07 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "Hi,\n\nOn 2020-09-05 11:15:07 +1200, Thomas Munro wrote:\n> On Sat, Sep 5, 2020 at 9:45 AM Andres Freund <andres@anarazel.de> wrote:\n> > On 2020-09-02 17:51:27 +0200, Juan Jos� Santamar�a Flecha wrote:\n> > > + attrib = GetFileAttributes(d->ret.d_name);\n> >\n> > Is this really an optimization? The benefit of Thomas' patch is that\n> > that information sometimes already is there. But here you're doing a\n> > separate lookup with GetFileAttributes()?\n> \n> Well as discussed already, our stat() emulation on Windows does\n> multiple syscalls, so it's a slight improvement.\n\nBut the patch is patching readdir(), not just walkdir(). Not all\nreaddir() / ReadDir() callers necessarily do a stat() and many continue\nto do a stat() after the patches. So for all of those except walkdir(),\nsome like RemoveOldXlogFiles() sometimes being noticable cost wise, the\npatch will increase the cost on windows. No? That's quite different\nfrom utilizing \"free\" information.\n\n\n> However, it looks like we might be missing a further opportunity\n> here... Doesn't Windows already give us the flags we need in the\n> dwFileAttributes member of the WIN32_FIND_DATA object that the\n> Find{First,Next}File() functions populate?\n\nThat'd be better...\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 4 Sep 2020 17:13:32 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "On Sat, Sep 5, 2020 at 2:13 AM Andres Freund <andres@anarazel.de> wrote:\n\n>\n> > However, it looks like we might be missing a further opportunity\n> > here... Doesn't Windows already give us the flags we need in the\n> > dwFileAttributes member of the WIN32_FIND_DATA object that the\n> > Find{First,Next}File() functions populate?\n>\n> That'd be better...\n>\n\nAt first I did not see how to get DT_LNK directly, but it is possible\nwithout additional calls, so please find attached a version with that logic.\n\nThis version also drops the enum, defining just the macros.\n\nRegards,\n\nJuan José Santamaría Flecha", "msg_date": "Sat, 5 Sep 2020 19:22:23 +0200", "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: A micro-optimisation for walkdir()" }, { "msg_contents": "On Sun, Sep 6, 2020 at 5:23 AM Juan José Santamaría Flecha\n<juanjo.santamaria@gmail.com> wrote:\n> On Sat, Sep 5, 2020 at 2:13 AM Andres Freund <andres@anarazel.de> wrote:\n>> > However, it looks like we might be missing a further opportunity\n>> > here... Doesn't Windows already give us the flags we need in the\n>> > dwFileAttributes member of the WIN32_FIND_DATA object that the\n>> > Find{First,Next}File() functions populate?\n>>\n>> That'd be better...\n>\n>\n> At first I did not see how to get DT_LNK directly, but it is possible without additional calls, so please find attached a version with that logic.\n>\n> This version also drops the enum, defining just the macros.\n\nExcellent. I'd like to commit these soon, unless someone has a better\nidea for how to name file_utils_febe.c.\n\nI think the following is a little mysterious, but it does seem to be\nwhat people do for this in other projects. It is the documented way\nto detect mount points, and I guess IO_REPARSE_TAG_MOUNT_POINT is\neither overloaded also for junctions, or junctions are the same thing\nas mount points. It would be nice to see a Win32 documentation page\nthat explicitly said that.\n\n+ /* For reparse points dwReserved0 field will contain the ReparseTag */\n+ else if ((fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0\n+ && (fd.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT))\n+ d->ret.d_type = DT_LNK;\n\nHmm, it's interesting that our existing test for a junction in\npgwin32_is_junction() only looks for FILE_ATTRIBUTE_REPARSE_POINT and\ndoesn't care what kind of reparse point it is.\n\n\n", "msg_date": "Mon, 7 Sep 2020 10:26:37 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "Thomas Munro <thomas.munro@gmail.com> writes:\n> Excellent. I'd like to commit these soon, unless someone has a better\n> idea for how to name file_utils_febe.c.\n\nAs long as it's in src/port or src/common, isn't it implicit that\nit's probably FE/BE common code?\n\nI think it'd make more sense to insert all this stuff into file_utils.c,\nand then just \"#ifdef FRONTEND\" the existing code there that doesn't work\nin backend. For one thing, that gives us a saner upgrade path whenever\nsomebody gets ambitious enough to make that code work for the backend.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 06 Sep 2020 18:36:14 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "On Mon, Sep 7, 2020 at 10:36 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Thomas Munro <thomas.munro@gmail.com> writes:\n> > Excellent. I'd like to commit these soon, unless someone has a better\n> > idea for how to name file_utils_febe.c.\n>\n> As long as it's in src/port or src/common, isn't it implicit that\n> it's probably FE/BE common code?\n>\n> I think it'd make more sense to insert all this stuff into file_utils.c,\n> and then just \"#ifdef FRONTEND\" the existing code there that doesn't work\n> in backend. For one thing, that gives us a saner upgrade path whenever\n> somebody gets ambitious enough to make that code work for the backend.\n\nTrue. Ok, I committed the Unix patch that way. I know it works on\nLinux, FreeBSD, macOS and Windows (without Juan José's patch), but\nI'll have to check the build farm later to make sure HPUX, AIX and\nSolaris are OK with this. It's remotely possible that one of them\ndefines DT_REG etc but doesn't have d_type; I'm hoping to get away\nwith not adding a configure check.\n\nI'll wait a bit longer for comments on the Windows patch.\n\n\n", "msg_date": "Mon, 7 Sep 2020 18:29:02 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "On Mon, Sep 7, 2020 at 12:27 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n\n> On Sun, Sep 6, 2020 at 5:23 AM Juan José Santamaría Flecha\n> <juanjo.santamaria@gmail.com> wrote:\n> > On Sat, Sep 5, 2020 at 2:13 AM Andres Freund <andres@anarazel.de> wrote:\n> >> > However, it looks like we might be missing a further opportunity\n> >> > here... Doesn't Windows already give us the flags we need in the\n> >> > dwFileAttributes member of the WIN32_FIND_DATA object that the\n> >> > Find{First,Next}File() functions populate?\n> >>\n> >> That'd be better...\n> >\n> >\n> > At first I did not see how to get DT_LNK directly, but it is possible\n> without additional calls, so please find attached a version with that logic.\n> >\n> > This version also drops the enum, defining just the macros.\n>\n> Excellent. I'd like to commit these soon, unless someone has a better\n> idea for how to name file_utils_febe.c.\n>\n> I think the following is a little mysterious, but it does seem to be\n> what people do for this in other projects. It is the documented way\n> to detect mount points, and I guess IO_REPARSE_TAG_MOUNT_POINT is\n> either overloaded also for junctions, or junctions are the same thing\n> as mount points. It would be nice to see a Win32 documentation page\n> that explicitly said that.\n>\n\nThe wikipedia page on it is actually fairly decent:\nhttps://en.wikipedia.org/wiki/NTFS_reparse_point. It's not the\ndocumentation of course, but it's easier to read :) The core difference is\nwhether you mount a whole filesystem (mount point) or just a directory off\nsomething mounted elsehwere (junction).\n\nAnd yes, the wikipedia page confirms that junctions also use\nIO_REPARSE_TAG_MOUNT_POINT.\n\n\n+ /* For reparse points dwReserved0 field will contain the ReparseTag */\n> + else if ((fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0\n> + && (fd.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT))\n> + d->ret.d_type = DT_LNK;\n>\n> Hmm, it's interesting that our existing test for a junction in\n> pgwin32_is_junction() only looks for FILE_ATTRIBUTE_REPARSE_POINT and\n> doesn't care what kind of reparse point it is.\n>\n\nI think that's mostly historical. When that code was written, the only two\ntypes of reparse points that existed were junctions and mount points --\nwhich are as already noted, the same. Symbolic links, unix sockets and such\nthings came later.\n\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 7, 2020 at 12:27 AM Thomas Munro <thomas.munro@gmail.com> wrote:On Sun, Sep 6, 2020 at 5:23 AM Juan José Santamaría Flecha\n<juanjo.santamaria@gmail.com> wrote:\n> On Sat, Sep 5, 2020 at 2:13 AM Andres Freund <andres@anarazel.de> wrote:\n>> > However, it looks like we might be missing a further opportunity\n>> > here...  Doesn't Windows already give us the flags we need in the\n>> > dwFileAttributes member of the WIN32_FIND_DATA object that the\n>> > Find{First,Next}File() functions populate?\n>>\n>> That'd be better...\n>\n>\n> At first I did not see how to get DT_LNK directly, but it is possible without additional calls, so please find attached a version with that logic.\n>\n> This version also drops the enum, defining just the macros.\n\nExcellent.  I'd like to commit these soon, unless someone has a better\nidea for how to name file_utils_febe.c.\n\nI think the following is a little mysterious, but it does seem to be\nwhat people do for this in other projects.  It is the documented way\nto detect mount points, and I guess IO_REPARSE_TAG_MOUNT_POINT is\neither overloaded also for junctions, or junctions are the same thing\nas mount points.  It would be nice to see a Win32 documentation page\nthat explicitly said that.The wikipedia page on it is actually fairly decent: https://en.wikipedia.org/wiki/NTFS_reparse_point. It's not the documentation of course, but it's easier to read :) The core difference is whether you mount a whole filesystem (mount point) or just a directory off something mounted elsehwere (junction).And yes, the wikipedia page confirms that junctions also use IO_REPARSE_TAG_MOUNT_POINT.\n+    /* For reparse points dwReserved0 field will contain the ReparseTag */\n+    else if ((fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0\n+             && (fd.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT))\n+        d->ret.d_type = DT_LNK;\n\nHmm, it's interesting that our existing test for a junction in\npgwin32_is_junction() only looks for FILE_ATTRIBUTE_REPARSE_POINT and\ndoesn't care what kind of reparse point it is.I think that's mostly historical. When that code was written, the only two types of reparse points that existed were junctions and mount points -- which are as already noted, the same. Symbolic links, unix sockets and such things came later. --  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Mon, 7 Sep 2020 11:42:04 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "On Mon, Sep 7, 2020 at 9:42 PM Magnus Hagander <magnus@hagander.net> wrote:\n> On Mon, Sep 7, 2020 at 12:27 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n>> I think the following is a little mysterious, but it does seem to be\n>> what people do for this in other projects. It is the documented way\n>> to detect mount points, and I guess IO_REPARSE_TAG_MOUNT_POINT is\n>> either overloaded also for junctions, or junctions are the same thing\n>> as mount points. It would be nice to see a Win32 documentation page\n>> that explicitly said that.\n>\n> The wikipedia page on it is actually fairly decent: https://en.wikipedia.org/wiki/NTFS_reparse_point. It's not the documentation of course, but it's easier to read :) The core difference is whether you mount a whole filesystem (mount point) or just a directory off something mounted elsehwere (junction).\n>\n> And yes, the wikipedia page confirms that junctions also use IO_REPARSE_TAG_MOUNT_POINT.\n\nThanks for confirming. I ran the Windows patch through pgindent,\nfixed a small typo, and pushed.\n\n\n", "msg_date": "Mon, 7 Sep 2020 23:40:47 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "On Mon, Sep 7, 2020 at 1:41 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n\n> On Mon, Sep 7, 2020 at 9:42 PM Magnus Hagander <magnus@hagander.net>\n> wrote:\n> > On Mon, Sep 7, 2020 at 12:27 AM Thomas Munro <thomas.munro@gmail.com>\n> wrote:\n> >> I think the following is a little mysterious, but it does seem to be\n> >> what people do for this in other projects. It is the documented way\n> >> to detect mount points, and I guess IO_REPARSE_TAG_MOUNT_POINT is\n> >> either overloaded also for junctions, or junctions are the same thing\n> >> as mount points. It would be nice to see a Win32 documentation page\n> >> that explicitly said that.\n> >\n> > The wikipedia page on it is actually fairly decent:\n> https://en.wikipedia.org/wiki/NTFS_reparse_point. It's not the\n> documentation of course, but it's easier to read :) The core difference is\n> whether you mount a whole filesystem (mount point) or just a directory off\n> something mounted elsehwere (junction).\n> >\n> > And yes, the wikipedia page confirms that junctions also use\n> IO_REPARSE_TAG_MOUNT_POINT.\n>\n> Thanks for confirming. I ran the Windows patch through pgindent,\n> fixed a small typo, and pushed.\n>\n\nGreat, thanks. Should we include something from this discussion as comments?\n\nRegards,\n\nJuan José Santamaría Flecha\n\nOn Mon, Sep 7, 2020 at 1:41 PM Thomas Munro <thomas.munro@gmail.com> wrote:On Mon, Sep 7, 2020 at 9:42 PM Magnus Hagander <magnus@hagander.net> wrote:\n> On Mon, Sep 7, 2020 at 12:27 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n>> I think the following is a little mysterious, but it does seem to be\n>> what people do for this in other projects.  It is the documented way\n>> to detect mount points, and I guess IO_REPARSE_TAG_MOUNT_POINT is\n>> either overloaded also for junctions, or junctions are the same thing\n>> as mount points.  It would be nice to see a Win32 documentation page\n>> that explicitly said that.\n>\n> The wikipedia page on it is actually fairly decent: https://en.wikipedia.org/wiki/NTFS_reparse_point. It's not the documentation of course, but it's easier to read :) The core difference is whether you mount a whole filesystem (mount point) or just a directory off something mounted elsehwere (junction).\n>\n> And yes, the wikipedia page confirms that junctions also use IO_REPARSE_TAG_MOUNT_POINT.\n\nThanks for confirming.  I ran the Windows patch through pgindent,\nfixed a small typo, and pushed.Great, thanks. Should we include something from this discussion as comments?Regards,Juan José Santamaría Flecha", "msg_date": "Mon, 7 Sep 2020 16:03:38 +0200", "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: A micro-optimisation for walkdir()" }, { "msg_contents": "On Tue, Sep 8, 2020 at 2:05 AM Juan José Santamaría Flecha\n<juanjo.santamaria@gmail.com> wrote:\n> On Mon, Sep 7, 2020 at 1:41 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n>> Thanks for confirming. I ran the Windows patch through pgindent,\n>> fixed a small typo, and pushed.\n>\n> Great, thanks. Should we include something from this discussion as comments?\n\nI dunno, it seems like this may be common knowledge for Windows people\nand I was just being paranoid by asking for more info as a\nnon-Windowsian, but if you want to propose new comments or perhaps\njust a pointer to one central place where we explain how that works, I\nwouldn't be against that.\n\nFWIW I just spotted a couple of very suspicious looking failures for\nbuild farm animal \"walleye\", a \"MinGW64 8.1.0\" system, that say:\n\nc:\\\\pgbuildfarm\\\\pgbuildroot\\\\HEAD\\\\pgsql.build\\\\src\\\\bin\\\\pg_upgrade>RMDIR\n/s/q \"c:\\\\pgbuildfarm\\\\pgbuildroot\\\\HEAD\\\\pgsql.build\\\\src\\\\bin\\\\pg_upgrade\\\\tmp_check\\\\data.old\"\nThe directory is not empty.\n\nThen I noticed it failed the same way 8 days ago, so I don't know\nwhat's up with that but it looks like we didn't break it...\n\n\n", "msg_date": "Tue, 8 Sep 2020 10:03:28 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "Thomas Munro <thomas.munro@gmail.com> writes:\n> FWIW I just spotted a couple of very suspicious looking failures for\n> build farm animal \"walleye\", a \"MinGW64 8.1.0\" system, that say:\n\nwalleye's been kind of unstable since the get-go, so I wouldn't put\ntoo much faith in reports just from it.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 07 Sep 2020 18:53:53 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "On Tue, Sep 8, 2020 at 10:53 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Thomas Munro <thomas.munro@gmail.com> writes:\n> > FWIW I just spotted a couple of very suspicious looking failures for\n> > build farm animal \"walleye\", a \"MinGW64 8.1.0\" system, that say:\n>\n> walleye's been kind of unstable since the get-go, so I wouldn't put\n> too much faith in reports just from it.\n\nCC'ing animal owner.\n\n<pokes at the logs> I suspect that someone who knows about PostgreSQL\non Windows would recognise the above symptom, but my guess is the\nWindows \"indexing\" service is on, or an antivirus thing, or some other\nkind of automatically-open-and-sniff-every-file-on-certain-file-events\nthing. It looks like nothing of ours is even running at that moment\n(\"waiting for server to shut down.... done\"), and it's the RMDIR /s\nshell command that is reporting the error. The other low probability\nerror seen on this host is this one:\n\n+ERROR: could not stat file \"pg_wal/000000010000000000000007\":\nPermission denied\n\n\n", "msg_date": "Mon, 14 Sep 2020 10:42:03 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: A micro-optimisation for walkdir()" }, { "msg_contents": "On Mon, Sep 14, 2020 at 12:42 AM Thomas Munro <thomas.munro@gmail.com>\nwrote:\n\n> On Tue, Sep 8, 2020 at 10:53 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > Thomas Munro <thomas.munro@gmail.com> writes:\n> > > FWIW I just spotted a couple of very suspicious looking failures for\n> > > build farm animal \"walleye\", a \"MinGW64 8.1.0\" system, that say:\n> >\n> > walleye's been kind of unstable since the get-go, so I wouldn't put\n> > too much faith in reports just from it.\n>\n> CC'ing animal owner.\n>\n> <pokes at the logs> I suspect that someone who knows about PostgreSQL\n> on Windows would recognise the above symptom, but my guess is the\n> Windows \"indexing\" service is on, or an antivirus thing, or some other\n> kind of automatically-open-and-sniff-every-file-on-certain-file-events\n> thing. It looks like nothing of ours is even running at that moment\n> (\"waiting for server to shut down.... done\"), and it's the RMDIR /s\n> shell command that is reporting the error. The other low probability\n> error seen on this host is this one:\n>\n> +ERROR: could not stat file \"pg_wal/000000010000000000000007\":\n> Permission denied\n>\n\nThis is a known problem, previous to this patch. There have been a couple\nof attempts to tackle it, and hopefully the shared-memory based stats\ncollector will take care of it:\n\nhttps://www.postgresql.org/message-id/18986.1585585020%40sss.pgh.pa.us\n\nRegards,\n\nJuan José Santamaría Flecha\n\nOn Mon, Sep 14, 2020 at 12:42 AM Thomas Munro <thomas.munro@gmail.com> wrote:On Tue, Sep 8, 2020 at 10:53 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Thomas Munro <thomas.munro@gmail.com> writes:\n> > FWIW I just spotted a couple of very suspicious looking failures for\n> > build farm animal \"walleye\", a \"MinGW64 8.1.0\" system, that say:\n>\n> walleye's been kind of unstable since the get-go, so I wouldn't put\n> too much faith in reports just from it.\n\nCC'ing animal owner.\n\n<pokes at the logs>  I suspect that someone who knows about PostgreSQL\non Windows would recognise the above symptom, but my guess is the\nWindows \"indexing\" service is on, or an antivirus thing, or some other\nkind of automatically-open-and-sniff-every-file-on-certain-file-events\nthing.  It looks like nothing of ours is even running at that moment\n(\"waiting for server to shut down.... done\"), and it's the RMDIR /s\nshell command that is reporting the error.  The other low probability\nerror seen on this host is this one:\n\n+ERROR:  could not stat file \"pg_wal/000000010000000000000007\":\nPermission deniedThis is a known problem, previous to this patch. There have been a couple of attempts to tackle it, and hopefully the shared-memory based stats collector will take care of it:https://www.postgresql.org/message-id/18986.1585585020%40sss.pgh.pa.usRegards,Juan José Santamaría Flecha", "msg_date": "Mon, 14 Sep 2020 09:51:54 +0200", "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: A micro-optimisation for walkdir()" } ]
[ { "msg_contents": "Hi,\n\non a regular basis I remember a builtin function's name, or can figure it out\nusing \\df etc, but can't remember the argument order. A typical example is\nregexp_*, where I never remember whether the pattern or the input string comes\nfirst.\n\nUnfortunatly \\df does not really help with that:\n\n=# \\df regexp_split_to_table\n┌────────────┬───────────────────────┬──────────────────┬─────────────────────┬──────┐\n│ Schema │ Name │ Result data type │ Argument data types │ Type │\n├────────────┼───────────────────────┼──────────────────┼─────────────────────┼──────┤\n│ pg_catalog │ regexp_split_to_table │ SETOF text │ text, text │ func │\n│ pg_catalog │ regexp_split_to_table │ SETOF text │ text, text, text │ func │\n└────────────┴───────────────────────┴──────────────────┴─────────────────────┴──────┘\n\nIf the parameters were named however, it'd be clear:\n\n=# CREATE OR REPLACE FUNCTION pg_catalog.regexp_split_to_table(string text, pattern text)\n RETURNS SETOF text\n LANGUAGE internal\n IMMUTABLE PARALLEL SAFE STRICT\nAS $function$regexp_split_to_table_no_flags$function$\n\n=# \\df regexp_split_to_table\n┌────────────┬───────────────────────┬──────────────────┬──────────────────────────┬──────┐\n│ Schema │ Name │ Result data type │ Argument data types │ Type │\n├────────────┼───────────────────────┼──────────────────┼──────────────────────────┼──────┤\n│ pg_catalog │ regexp_split_to_table │ SETOF text │ string text, pattern text │ func │\n│ pg_catalog │ regexp_split_to_table │ SETOF text │ text, text, text │ func │\n└────────────┴───────────────────────┴──────────────────┴──────────────────────────┴──────┘\n\n(I intentionally left the three parameter version unchanged, to show the difference)\n\n\nIn the docs we already name the parameters using SQL like syntax, see [1]. How\nabout we actually do so for at least the more common / complicated functions?\nIt may not be worth adding operator names for every comparator, but for\nfunctions we expect to be used directly it seems worthwhile?\n\nIt sure would be some initial work, but it seems doable.\n\nComments?\n\n\nA mildly related note: It's a bit annoying that the \"Pattern Matching\"\ndocumentation page [2] does not appear to contain a link to the documentation\nabout the individual pattern matching functions [1]. Am I missing something?\n\nGreetings,\n\nAndres Freund\n\n[1] https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-OTHER\n[2] https://www.postgresql.org/docs/current/functions-matching.html\n\n\n", "msg_date": "Tue, 1 Sep 2020 22:35:05 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "builtin functions, parameter names and psql's \\df" }, { "msg_contents": "On Wed, Sep 2, 2020 at 7:35 AM Andres Freund <andres@anarazel.de> wrote:\r\n\r\n> Hi,\r\n>\r\n> on a regular basis I remember a builtin function's name, or can figure it\r\n> out\r\n> using \\df etc, but can't remember the argument order. A typical example is\r\n> regexp_*, where I never remember whether the pattern or the input string\r\n> comes\r\n> first.\r\n>\r\n> Unfortunatly \\df does not really help with that:\r\n>\r\n> =# \\df regexp_split_to_table\r\n>\r\n> ┌────────────┬───────────────────────┬──────────────────┬─────────────────────┬──────┐\r\n> │ Schema │ Name │ Result data type │ Argument data\r\n> types │ Type │\r\n>\r\n> ├────────────┼───────────────────────┼──────────────────┼─────────────────────┼──────┤\r\n> │ pg_catalog │ regexp_split_to_table │ SETOF text │ text, text\r\n> │ func │\r\n> │ pg_catalog │ regexp_split_to_table │ SETOF text │ text, text,\r\n> text │ func │\r\n>\r\n> └────────────┴───────────────────────┴──────────────────┴─────────────────────┴──────┘\r\n>\r\n> If the parameters were named however, it'd be clear:\r\n>\r\n> =# CREATE OR REPLACE FUNCTION pg_catalog.regexp_split_to_table(string\r\n> text, pattern text)\r\n> RETURNS SETOF text\r\n> LANGUAGE internal\r\n> IMMUTABLE PARALLEL SAFE STRICT\r\n> AS $function$regexp_split_to_table_no_flags$function$\r\n>\r\n> =# \\df regexp_split_to_table\r\n>\r\n> ┌────────────┬───────────────────────┬──────────────────┬──────────────────────────┬──────┐\r\n> │ Schema │ Name │ Result data type │ Argument data\r\n> types │ Type │\r\n>\r\n> ├────────────┼───────────────────────┼──────────────────┼──────────────────────────┼──────┤\r\n> │ pg_catalog │ regexp_split_to_table │ SETOF text │ string text,\r\n> pattern text │ func │\r\n> │ pg_catalog │ regexp_split_to_table │ SETOF text │ text, text,\r\n> text │ func │\r\n>\r\n> └────────────┴───────────────────────┴──────────────────┴──────────────────────────┴──────┘\r\n>\r\n> (I intentionally left the three parameter version unchanged, to show the\r\n> difference)\r\n>\r\n>\r\n> In the docs we already name the parameters using SQL like syntax, see [1].\r\n> How\r\n> about we actually do so for at least the more common / complicated\r\n> functions?\r\n>\r\n\r\n+many\r\n\r\nI find myself in the same situation a lot.\r\nI've never realized that's an implementation detail and not something\r\nfundamental preventing the parameters from being named in the built-in\r\nfunctions.\r\n\r\n--\r\nAlex\r\n\nOn Wed, Sep 2, 2020 at 7:35 AM Andres Freund <andres@anarazel.de> wrote:Hi,\n\r\non a regular basis I remember a builtin function's name, or can figure it out\r\nusing \\df etc, but can't remember the argument order. A typical example is\r\nregexp_*, where I never remember whether the pattern or the input string comes\r\nfirst.\n\r\nUnfortunatly \\df does not really help with that:\n\r\n=# \\df regexp_split_to_table\r\n┌────────────┬───────────────────────┬──────────────────┬─────────────────────┬──────┐\r\n│   Schema   │         Name          │ Result data type │ Argument data types │ Type │\r\n├────────────┼───────────────────────┼──────────────────┼─────────────────────┼──────┤\r\n│ pg_catalog │ regexp_split_to_table │ SETOF text       │ text, text          │ func │\r\n│ pg_catalog │ regexp_split_to_table │ SETOF text       │ text, text, text    │ func │\r\n└────────────┴───────────────────────┴──────────────────┴─────────────────────┴──────┘\n\r\nIf the parameters were named however, it'd be clear:\n\r\n=# CREATE OR REPLACE FUNCTION pg_catalog.regexp_split_to_table(string text, pattern text)\r\n RETURNS SETOF text\r\n LANGUAGE internal\r\n IMMUTABLE PARALLEL SAFE STRICT\r\nAS $function$regexp_split_to_table_no_flags$function$\n\r\n=# \\df regexp_split_to_table\r\n┌────────────┬───────────────────────┬──────────────────┬──────────────────────────┬──────┐\r\n│   Schema   │         Name          │ Result data type │   Argument data types    │ Type │\r\n├────────────┼───────────────────────┼──────────────────┼──────────────────────────┼──────┤\r\n│ pg_catalog │ regexp_split_to_table │ SETOF text       │ string text, pattern text │ func │\r\n│ pg_catalog │ regexp_split_to_table │ SETOF text       │ text, text, text         │ func │\r\n└────────────┴───────────────────────┴──────────────────┴──────────────────────────┴──────┘\n\r\n(I intentionally left the three parameter version unchanged, to show the difference)\n\n\r\nIn the docs we already name the parameters using SQL like syntax, see [1]. How\r\nabout we actually do so for at least the more common / complicated functions?+many I find myself in the same situation a lot.I've never realized that's an implementation detail and not something fundamental preventing the parameters from being named in the built-in functions.--Alex", "msg_date": "Wed, 2 Sep 2020 09:13:00 +0200", "msg_from": "Oleksandr Shulgin <oleksandr.shulgin@zalando.de>", "msg_from_op": false, "msg_subject": "Re: builtin functions, parameter names and psql's \\df" }, { "msg_contents": "On Wed, Sep 2, 2020 at 9:13 AM Oleksandr Shulgin\r\n<oleksandr.shulgin@zalando.de> wrote:\r\n>\r\n> On Wed, Sep 2, 2020 at 7:35 AM Andres Freund <andres@anarazel.de> wrote:\r\n>>\r\n>> Hi,\r\n>>\r\n>> on a regular basis I remember a builtin function's name, or can figure it out\r\n>> using \\df etc, but can't remember the argument order. A typical example is\r\n>> regexp_*, where I never remember whether the pattern or the input string comes\r\n>> first.\r\n>>\r\n>> Unfortunatly \\df does not really help with that:\r\n>>\r\n>> =# \\df regexp_split_to_table\r\n>> ┌────────────┬───────────────────────┬──────────────────┬─────────────────────┬──────┐\r\n>> │ Schema │ Name │ Result data type │ Argument data types │ Type │\r\n>> ├────────────┼───────────────────────┼──────────────────┼─────────────────────┼──────┤\r\n>> │ pg_catalog │ regexp_split_to_table │ SETOF text │ text, text │ func │\r\n>> │ pg_catalog │ regexp_split_to_table │ SETOF text │ text, text, text │ func │\r\n>> └────────────┴───────────────────────┴──────────────────┴─────────────────────┴──────┘\r\n>>\r\n>> If the parameters were named however, it'd be clear:\r\n>>\r\n>> =# CREATE OR REPLACE FUNCTION pg_catalog.regexp_split_to_table(string text, pattern text)\r\n>> RETURNS SETOF text\r\n>> LANGUAGE internal\r\n>> IMMUTABLE PARALLEL SAFE STRICT\r\n>> AS $function$regexp_split_to_table_no_flags$function$\r\n>>\r\n>> =# \\df regexp_split_to_table\r\n>> ┌────────────┬───────────────────────┬──────────────────┬──────────────────────────┬──────┐\r\n>> │ Schema │ Name │ Result data type │ Argument data types │ Type │\r\n>> ├────────────┼───────────────────────┼──────────────────┼──────────────────────────┼──────┤\r\n>> │ pg_catalog │ regexp_split_to_table │ SETOF text │ string text, pattern text │ func │\r\n>> │ pg_catalog │ regexp_split_to_table │ SETOF text │ text, text, text │ func │\r\n>> └────────────┴───────────────────────┴──────────────────┴──────────────────────────┴──────┘\r\n>>\r\n>> (I intentionally left the three parameter version unchanged, to show the difference)\r\n>>\r\n>>\r\n>> In the docs we already name the parameters using SQL like syntax, see [1]. How\r\n>> about we actually do so for at least the more common / complicated functions?\r\n>\r\n>\r\n> +many\r\n>\r\n> I find myself in the same situation a lot.\r\n> I've never realized that's an implementation detail and not something fundamental preventing the parameters from being named in the built-in functions.\r\n\r\nSame here, it would be a very nice improvement.\r\n", "msg_date": "Wed, 2 Sep 2020 09:15:12 +0200", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: builtin functions, parameter names and psql's \\df" }, { "msg_contents": "On 02/09/2020 19:15, Julien Rouhaud wrote:\n> On Wed, Sep 2, 2020 at 9:13 AM Oleksandr Shulgin\n> <oleksandr.shulgin@zalando.de> wrote:\n>> On Wed, Sep 2, 2020 at 7:35 AM Andres Freund <andres@anarazel.de> wrote:\n>>> Hi,\n>>>\n>>> on a regular basis I remember a builtin function's name, or can figure it out\n>>> using \\df etc, but can't remember the argument order. A typical example is\n>>> regexp_*, where I never remember whether the pattern or the input string comes\n>>> first.\n>>>\n>>> Unfortunatly \\df does not really help with that:\n>>>\n>>> =# \\df regexp_split_to_table\n>>> ┌────────────┬───────────────────────┬──────────────────┬─────────────────────┬──────┐\n>>> │ Schema │ Name │ Result data type │ Argument data types │ Type │\n>>> ├────────────┼───────────────────────┼──────────────────┼─────────────────────┼──────┤\n>>> │ pg_catalog │ regexp_split_to_table │ SETOF text │ text, text │ func │\n>>> │ pg_catalog │ regexp_split_to_table │ SETOF text │ text, text, text │ func │\n>>> └────────────┴───────────────────────┴──────────────────┴─────────────────────┴──────┘\n>>>\n>>> If the parameters were named however, it'd be clear:\n>>>\n>>> =# CREATE OR REPLACE FUNCTION pg_catalog.regexp_split_to_table(string text, pattern text)\n>>> RETURNS SETOF text\n>>> LANGUAGE internal\n>>> IMMUTABLE PARALLEL SAFE STRICT\n>>> AS $function$regexp_split_to_table_no_flags$function$\n>>>\n>>> =# \\df regexp_split_to_table\n>>> ┌────────────┬───────────────────────┬──────────────────┬──────────────────────────┬──────┐\n>>> │ Schema │ Name │ Result data type │ Argument data types │ Type │\n>>> ├────────────┼───────────────────────┼──────────────────┼──────────────────────────┼──────┤\n>>> │ pg_catalog │ regexp_split_to_table │ SETOF text │ string text, pattern text │ func │\n>>> │ pg_catalog │ regexp_split_to_table │ SETOF text │ text, text, text │ func │\n>>> └────────────┴───────────────────────┴──────────────────┴──────────────────────────┴──────┘\n>>>\n>>> (I intentionally left the three parameter version unchanged, to show the difference)\n>>>\n>>>\n>>> In the docs we already name the parameters using SQL like syntax, see [1]. How\n>>> about we actually do so for at least the more common / complicated functions?\n>>\n>> +many\n>>\n>> I find myself in the same situation a lot.\n>> I've never realized that's an implementation detail and not something fundamental preventing the parameters from being named in the built-in functions.\n> Same here, it would be a very nice improvement.\n\n+1\n\n\n\n", "msg_date": "Wed, 2 Sep 2020 19:35:18 +1200", "msg_from": "Gavin Flower <GavinFlower@archidevsys.co.nz>", "msg_from_op": false, "msg_subject": "Re: builtin functions, parameter names and psql's \\df" }, { "msg_contents": "Oleksandr Shulgin <oleksandr.shulgin@zalando.de> writes:\n> On Wed, Sep 2, 2020 at 7:35 AM Andres Freund <andres@anarazel.de> wrote:\n>> In the docs we already name the parameters using SQL like syntax, see [1].\n>> How about we actually do so for at least the more common / complicated\n>> functions?\n\n> I find myself in the same situation a lot.\n> I've never realized that's an implementation detail and not something\n> fundamental preventing the parameters from being named in the built-in\n> functions.\n\nYeah, it's not really hard to fix; somebody just has to do the legwork.\nThe attached is enough to get me to\n\nregression=# \\df regexp_split_to_table\n List of functions\n Schema | Name | Result data type | Argument data types | Type \n------------+-----------------------+------------------+---------------------------------------+------\n pg_catalog | regexp_split_to_table | SETOF text | string text, pattern text | func\n pg_catalog | regexp_split_to_table | SETOF text | string text, pattern text, flags text | func\n(2 rows)\n\nI don't think we should go overboard on this, but +1 for labeling all the\ncases where the usage isn't obvious.\n\n\t\t\tregards, tom lane", "msg_date": "Wed, 02 Sep 2020 11:01:16 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: builtin functions, parameter names and psql's \\df" }, { "msg_contents": "On 2020-Sep-02, Tom Lane wrote:\n\n> I don't think we should go overboard on this, but +1 for labeling all the\n> cases where the usage isn't obvious.\n\n+1\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 2 Sep 2020 13:56:26 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: builtin functions, parameter names and psql's \\df" } ]
[ { "msg_contents": "Hi all,\n\n$subject has been mentioned a couple of times, including today:\nhttps://www.postgresql.org/message-id/20200902010012.GE1489@paquier.xyz\n\nWe have a boolean argument in ReindexStmt to control a concurrent\nrun, and we also have in parallel of that a bitmask to control the\noptions of the statement, which feels like a duplicate. Attached is a\npatch to refactor the whole, adding CONCURRENTLY as a member of the\navailable options. This simplifies a bit the code.\n\nAny thoughts?\n--\nMichael", "msg_date": "Wed, 2 Sep 2020 20:03:26 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Refactor ReindexStmt and its \"concurrent\" boolean" }, { "msg_contents": "On Wed, Sep 2, 2020 at 1:03 PM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> Hi all,\n>\n> $subject has been mentioned a couple of times, including today:\n> https://www.postgresql.org/message-id/20200902010012.GE1489@paquier.xyz\n>\n> We have a boolean argument in ReindexStmt to control a concurrent\n> run, and we also have in parallel of that a bitmask to control the\n> options of the statement, which feels like a duplicate. Attached is a\n> patch to refactor the whole, adding CONCURRENTLY as a member of the\n> available options. This simplifies a bit the code.\n>\n> Any thoughts?\n\n\n+1\n\n struct ReindexIndexCallbackState\n {\n- bool concurrent; /* flag from statement */\n+ bool options; /* flag from statement */\n Oid locked_table_oid; /* tracks previously locked table */\n };\n\nShouldn't options be an int? The rest of the patch looks good to me.\n\n\n", "msg_date": "Wed, 2 Sep 2020 13:17:32 +0200", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Refactor ReindexStmt and its \"concurrent\" boolean" }, { "msg_contents": "On Wed, Sep 02, 2020 at 01:17:32PM +0200, Julien Rouhaud wrote:\n> Shouldn't options be an int? The rest of the patch looks good to me.\n\nIt should, thanks for looking at it. Let's wait a couple of days and\nsee if others have any comments. If there are no objections, I'll try\nto commit this one.\n--\nMichael", "msg_date": "Thu, 3 Sep 2020 11:14:38 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Refactor ReindexStmt and its \"concurrent\" boolean" }, { "msg_contents": "On Thu, Sep 03, 2020 at 11:14:38AM +0900, Michael Paquier wrote:\n> It should, thanks for looking at it. Let's wait a couple of days and\n> see if others have any comments. If there are no objections, I'll try\n> to commit this one.\n\nAnd applied.\n--\nMichael", "msg_date": "Fri, 4 Sep 2020 10:51:39 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Refactor ReindexStmt and its \"concurrent\" boolean" } ]
[ { "msg_contents": "Hi,\n\nFirst, on behalf of the PostgreSQL 13 RMT, thank you everyone for your\nhard work not only building all of the features that are going into\nPostgreSQL 13, but for the diligence and work in stabilizing the\nrelease. We have now reached the point of the release cycle where we can\nstart making decisions about GA (general availability).\n\nBased on the current state and progress of the open items[1], the RMT\nwith consultation from the release team has decided to forgo a Beta 4\nrelease. Instead, we propose the following schedule:\n\n* PostgreSQL 13 Release Candidate 1 (RC1) will be released on September\n17, 2020.\n\n* In absence of any critical issues, PostgreSQL 13 will become generally\navailable on September 24, 2020.\n\nThe aim is to have all outstanding open items committed before RC1.\nPlease ensure everything is committed by September 16, 2020 AoE. We will\nsend out a reminder prior to that date.\n\nWe're very excited that we are in the final phase of the PostgreSQL 13\nlaunch. Thank you again for making this possible.\n\nSincerely,\n\nAlvaro, Peter, Jonathan\n\n[1] https://wiki.postgresql.org/wiki/PostgreSQL_13_Open_Items", "msg_date": "Wed, 2 Sep 2020 14:13:03 -0400", "msg_from": "\"Jonathan S. Katz\" <jkatz@postgresql.org>", "msg_from_op": true, "msg_subject": "PostgreSQL 13 Release Timeline" }, { "msg_contents": "Hi,\n\nOn 9/2/20 2:13 PM, Jonathan S. Katz wrote:\n\n> * PostgreSQL 13 Release Candidate 1 (RC1) will be released on September\n> 17, 2020.\n> \n> * In absence of any critical issues, PostgreSQL 13 will become generally\n> available on September 24, 2020.\n> \n> The aim is to have all outstanding open items committed before RC1.\n> Please ensure everything is committed by September 16, 2020 AoE. We will\n> send out a reminder prior to that date.\n\nAs a friendly reminder, RC1 is one week away. I also realized I made an\nerror in the commit date above for RC1. Sorry :( Corrected date below.\n\nPlease ensure you have all of your commits in by **September 13, 2020\nAoE** so we can wrap RC1 and get it out the door.\n\nPresuming RC1 is successful, commits for GA must be in by **September\n20, 2020 AoE**.\n\nPlease try to close out open items[1] before RC1.\n\nThanks!\n\nJonathan\n\n[1] https://wiki.postgresql.org/wiki/PostgreSQL_13_Open_Items", "msg_date": "Thu, 10 Sep 2020 13:08:30 -0400", "msg_from": "\"Jonathan S. Katz\" <jkatz@postgresql.org>", "msg_from_op": true, "msg_subject": "Re: PostgreSQL 13 Release Timeline" }, { "msg_contents": "On 9/10/20 1:08 PM, Jonathan S. Katz wrote:\n> Hi,\n> \n> On 9/2/20 2:13 PM, Jonathan S. Katz wrote:\n> \n>> * PostgreSQL 13 Release Candidate 1 (RC1) will be released on September\n>> 17, 2020.\n>>\n>> * In absence of any critical issues, PostgreSQL 13 will become generally\n>> available on September 24, 2020.\n>>\n>> The aim is to have all outstanding open items committed before RC1.\n>> Please ensure everything is committed by September 16, 2020 AoE. We will\n>> send out a reminder prior to that date.\n> \n> As a friendly reminder, RC1 is one week away. I also realized I made an\n> error in the commit date above for RC1. Sorry :( Corrected date below.\n> \n> Please ensure you have all of your commits in by **September 13, 2020\n> AoE** so we can wrap RC1 and get it out the door.\n> \n> Presuming RC1 is successful, commits for GA must be in by **September\n> 20, 2020 AoE**.\n> \n> Please try to close out open items[1] before RC1.\n\nI am pleased to report that PostgreSQL 13 is now GA:\n\nhttps://www.postgresql.org/about/news/2077/\n\nThank you everyone for your hard work and congratulations on another\nsuccessful release!\n\nJonathan", "msg_date": "Thu, 24 Sep 2020 09:29:57 -0400", "msg_from": "\"Jonathan S. Katz\" <jkatz@postgresql.org>", "msg_from_op": true, "msg_subject": "Re: PostgreSQL 13 Release Timeline" }, { "msg_contents": "> I am pleased to report that PostgreSQL 13 is now GA:\n>\n> https://www.postgresql.org/about/news/2077/\n>\n> Thank you everyone for your hard work and congratulations on another\n> successful release!\n\nWell done team!\n\n-- \nSimon Riggs http://www.2ndQuadrant.com/\nMission Critical Databases\n\n\n", "msg_date": "Thu, 24 Sep 2020 14:38:51 +0100", "msg_from": "Simon Riggs <simon@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: PostgreSQL 13 Release Timeline" }, { "msg_contents": "On Thu, Sep 24, 2020 at 9:30 AM Jonathan S. Katz <jkatz@postgresql.org> wrote:\n>\n> I am pleased to report that PostgreSQL 13 is now GA:\n>\n> https://www.postgresql.org/about/news/2077/\n\nI'm not sure if there was a \"release announcement draft\" thread\n(searching my folder didn't find one for GA, but it's also easily\npossible I missed it): I'm wondering if the link for incremental sort\n[1] should instead/also point to the examples in [2] which actually\nexplain what incremental sort does.\n\nActually, should the GUC page link there? There's not an obvious\nanchor tag on the page (that I can tell) to use for such a link\nthough...\n\nIf it'd be better to split off this to a new thread, I can do that too.\n\nJames\n\n1: https://www.postgresql.org/docs/13/runtime-config-query.html#GUC-ENABLE-INCREMENTAL-SORT\n2: https://www.postgresql.org/docs/13/using-explain.html\n\n\n", "msg_date": "Thu, 24 Sep 2020 10:11:45 -0400", "msg_from": "James Coleman <jtc331@gmail.com>", "msg_from_op": false, "msg_subject": "Re: PostgreSQL 13 Release Timeline" }, { "msg_contents": "On 9/24/20 10:11 AM, James Coleman wrote:\n> On Thu, Sep 24, 2020 at 9:30 AM Jonathan S. Katz <jkatz@postgresql.org> wrote:\n>>\n>> I am pleased to report that PostgreSQL 13 is now GA:\n>>\n>> https://www.postgresql.org/about/news/2077/\n> \n> I'm not sure if there was a \"release announcement draft\" thread\n> (searching my folder didn't find one for GA, but it's also easily\n> possible I missed it)\n\nYes, there always is[1]\n\n: I'm wondering if the link for incremental sort\n> [1] should instead/also point to the examples in [2] which actually\n> explain what incremental sort does.\n>\n> \n> Actually, should the GUC page link there? There's not an obvious\n> anchor tag on the page (that I can tell) to use for such a link\n> though...\n\nWhen researching it, I believe I chose the GUC because it was anchorable.\n\n> If it'd be better to split off this to a new thread, I can do that too.\n\nProbably, because it will trigger discussion ;)\n\nJonathan\n\n[1]\nhttps://www.postgresql.org/message-id/dfc987e3-bb8c-96f5-3bd2-11b9dcc96f19%40postgresql.org", "msg_date": "Thu, 24 Sep 2020 10:14:12 -0400", "msg_from": "\"Jonathan S. Katz\" <jkatz@postgresql.org>", "msg_from_op": true, "msg_subject": "Re: PostgreSQL 13 Release Timeline" } ]
[ { "msg_contents": "Hi,\n\nIs possible that BTreeTupleSetNAtts, leave everything tidy, so that\nBTreeTupleGetHeapTID doesn't fail.\nBTreeTupleGetHeapTID can return NULL.\n\nBut, as we can see:\n1. Line 2085 (nbtutils.c):\n if (BTreeTupleGetHeapTID(itup) != NULL && tupnatts != nkeyatts)\n2. Line 803 (nbtsearch.c):\n if (heapTid == NULL)\n\nMaybe, better make sure, because:\n3. Line 2285 (nbtutils.c):\n ItemPointerCopy(BTreeTupleGetMaxHeapTID(lastleft), pivotheaptid);\n4. Line 2316 (nbtutils.c) :\n ItemPointerCopy(BTreeTupleGetHeapTID(firstright), pivotheaptid);\n\nCan dereference NULL pointer (pivotheaptid) at runtime (release version).\n\nitemptr.h:\n#define ItemPointerCopy(fromPointer, toPointer) \\\n( \\\nAssertMacro(PointerIsValid(toPointer)), \\\nAssertMacro(PointerIsValid(fromPointer)), \\\n*(toPointer) = *(fromPointer) \\\n)\n\nregards,\nRanier Vilela\n\nHi,Is possible that BTreeTupleSetNAtts, \nleave everything tidy, so that BTreeTupleGetHeapTID doesn't fail.\nBTreeTupleGetHeapTID can return NULL.But, as we can see:1. Line 2085 (nbtutils.c):    if (BTreeTupleGetHeapTID(itup) != NULL && tupnatts != nkeyatts)2. Line 803 (nbtsearch.c):    if (heapTid == NULL)Maybe, better make sure, because:3. Line 2285 (nbtutils.c):    ItemPointerCopy(BTreeTupleGetMaxHeapTID(lastleft), pivotheaptid);4. Line 2316 \n(nbtutils.c)\n\n:    ItemPointerCopy(BTreeTupleGetHeapTID(firstright), pivotheaptid);Can dereference NULL pointer (pivotheaptid) at runtime (release version).itemptr.h:#define ItemPointerCopy(fromPointer, toPointer) \\( \\\tAssertMacro(PointerIsValid(toPointer)), \\\tAssertMacro(PointerIsValid(fromPointer)), \\\t*(toPointer) = *(fromPointer) \\)regards,Ranier Vilela", "msg_date": "Wed, 2 Sep 2020 18:39:09 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "[NBTREE] Possible NULL pointer dereference\n (backend/access/nbtree/nbutils.c)" }, { "msg_contents": "Also, in:\n5. Line 2671 (nbtutils.c):\n ItemPointerGetBlockNumber(BTreeTupleGetHeapTID(newtup)),\n ItemPointerGetOffsetNumber(BTreeTupleGetHeapTID(newtup)),\n\nitemptr.h:\n/*\n * ItemPointerGetBlockNumberNoCheck\n * Returns the block number of a disk item pointer.\n */\n#define ItemPointerGetBlockNumberNoCheck(pointer) \\\n( \\\nBlockIdGetBlockNumber(&(pointer)->ip_blkid) \\\n)\n\n#define ItemPointerGetOffsetNumberNoCheck(pointer) \\\n( \\\n(pointer)->ip_posid \\\n)\n\nregards,\nRanier Vilela\n\nAlso, in:5. Line 2671 (nbtutils.c):\t\t\t\t\t   ItemPointerGetBlockNumber(BTreeTupleGetHeapTID(newtup)),\t\t\t\t\t   ItemPointerGetOffsetNumber(BTreeTupleGetHeapTID(newtup)),itemptr.h:/* * ItemPointerGetBlockNumberNoCheck *\t\tReturns the block number of a disk item pointer. */#define ItemPointerGetBlockNumberNoCheck(pointer) \\( \\\tBlockIdGetBlockNumber(&(pointer)->ip_blkid) \\)#define ItemPointerGetOffsetNumberNoCheck(pointer) \\( \\\t(pointer)->ip_posid \\)regards,Ranier Vilela", "msg_date": "Wed, 2 Sep 2020 18:46:40 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Re: [NBTREE] Possible NULL pointer dereference\n (backend/access/nbtree/nbutils.c)" }, { "msg_contents": "On Wed, Sep 2, 2020 at 2:41 PM Ranier Vilela <ranier.vf@gmail.com> wrote:\n> Maybe, better make sure, because:\n> 3. Line 2285 (nbtutils.c):\n> ItemPointerCopy(BTreeTupleGetMaxHeapTID(lastleft), pivotheaptid);\n> 4. Line 2316 (nbtutils.c) :\n> ItemPointerCopy(BTreeTupleGetHeapTID(firstright), pivotheaptid);\n>\n> Can dereference NULL pointer (pivotheaptid) at runtime (release version).\n\nThe entire codepath in question exists to set a new pivot tuple's heap\nTID, in the case where we have to include a heap TID in a new leaf\npage high key. This is a tuple in palloc()'d memory that we ourselves\njust created.\n\nWe know that BTreeTupleGetHeapTID() will return a valid heap TID\npointer (a pointer into the end of the new pivot tuple buffer) because\nwe just marked the pivot tuple as having space for one ourselves -- we\nstill completely own the tuple. While it's true that in general\nBTreeTupleGetHeapTID() can return a NULL pointer, it does not matter\nhere. Even if BTreeTupleGetHeapTID() did somehow return a NULL\npointer, then the user would be getting off lightly by experiencing a\nhard crash instead of data corruption.\n\nYou should spend more time (as in more than zero time) trying to\nunderstand the intent of the code that you write these reports about.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Wed, 2 Sep 2020 15:05:01 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: [NBTREE] Possible NULL pointer dereference\n (backend/access/nbtree/nbutils.c)" }, { "msg_contents": "> Even if BTreeTupleGetHeapTID() did somehow return a NULL\n> pointer, then the user would be getting off lightly by experiencing a\n> hard crash instead of data corruption.\n>\nOh, I'm sorry, I thought that \"hard crash\" was a bad thing.\n\nRanier Vilela\n\nEven if BTreeTupleGetHeapTID() did somehow return a NULL\npointer, then the user would be getting off lightly by experiencing a\nhard crash instead of data corruption.Oh, I'm sorry, I thought that \"hard crash\" was a bad thing.Ranier Vilela", "msg_date": "Wed, 2 Sep 2020 19:14:00 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Re: [NBTREE] Possible NULL pointer dereference\n (backend/access/nbtree/nbutils.c)" }, { "msg_contents": "On Wed, Sep 2, 2020 at 3:16 PM Ranier Vilela <ranier.vf@gmail.com> wrote:\n> Oh, I'm sorry, I thought that \"hard crash\" was a bad thing.\n\nI think that you are being sarcastic here, but just in case I'm wrong\nI'll clarify what I meant: a good sign that a static analysis tool has\nproduced a useless complaint is that it appears to prove something far\nstronger than you first thought possible. You should look out for\nthat. This is just a heuristic, but in practice it is a good one.\nPerhaps you recall our discussion of a similar false positive in\nnbtsplitloc.c; that had a similar feel to it. For example, if your\nstatic analysis tool says that code that has been around for many\nyears is riddled with bugs, then the problem is almost certainly with\nthe tool (or with how the tool has been used).\n\nHigh performance C code very often relies on representational\ninvariants that may not be readily apparent to a compiler --\nespecially when dealing with on-disk state. Barring some obvious\nproblem like a hard crash, you have to do the work of assessing if the\ncode is correct based on the actual assumptions/context of the code. A\nstatic analysis tool is of very little use if you're not going to put\nthe work in. I went to a lot of trouble to clearly document the code\nin question here (the heap TID stuff in _bt_truncate()) -- did you\neven bother to read those comments once?\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Wed, 2 Sep 2020 16:16:56 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: [NBTREE] Possible NULL pointer dereference\n (backend/access/nbtree/nbutils.c)" }, { "msg_contents": "Em qua., 2 de set. de 2020 às 20:17, Peter Geoghegan <pg@bowt.ie> escreveu:\n\n> On Wed, Sep 2, 2020 at 3:16 PM Ranier Vilela <ranier.vf@gmail.com> wrote:\n\n\n\n> Perhaps you recall our discussion of a similar false positive in\n> nbtsplitloc.c; that had a similar feel to it. For example, if your\n> static analysis tool says that code that has been around for many\n> years is riddled with bugs, then the problem is almost certainly with\n> the tool (or with how the tool has been used).\n>\nI'm using about 4 static analysis tools.\nOnly one of them has a report of 67690 pages.\nAssuming an optimistic trend, only 1% could be real failures.\nIt would have 670 real flaws in the entire code.\nIn addition, if the code is compiled with -Wextra, hundreds of type\nmismatch alerts will be reported,\nespecially comparison between int (signed) and unsigned types.\n\nIf you try to leaks, you will find this:\n== 42483 == ERROR: LeakSanitizer: detected memory leaks\n\nDirect leak of 576 byte (s) in 1 object (s) allocated from:\n # 0 0x7f3204fb7bc8 in malloc\n(/lib/x86_64-linux-gnu/libasan.so.5+0x10dbc8)\n # 1 0x561c58d5b766 in save_ps_display_args\n/usr/src/postgres/src/backend/utils/misc/ps_status.c:178\n # 2 0x561c584a90b3 in main /usr/src/postgres/src/backend/main/main.c:89\n # 3 0x7f3204b7f0b2 in __libc_start_main\n(/lib/x86_64-linux-gnu/libc.so.6+0x270b2)\n\nIndirect leak of 14 byte (s) in 1 object (s) allocated from:\n # 0 0x7f3204f403dd in strdup\n(/lib/x86_64-linux-gnu/libasan.so.5+0x963dd)\n # 1 0x561c58d5b817 in save_ps_display_args\n/usr/src/postgres/src/backend/utils/misc/ps_status.c:186\n # 2 0x561c584a90b3 in main /usr/src/postgres/src/backend/main/main.c:89\n # 3 0x7f3204b7f0b2 in __libc_start_main\n(/lib/x86_64-linux-gnu/libc.so.6+0x270b2)\n\nFor each reported failure, I have analyzed the code, without focusing on\nthe \"intention of the code\",\nbut trying to abstract and concentrate on following the flow of the\nvariables to make sure that the alert is invalid.\nMaybe I didn't realize it, but I'm not \"getting out of my head\", these\nalerts.\n\n\n>\n> High performance C code very often relies on representational\n> invariants that may not be readily apparent to a compiler --\n> especially when dealing with on-disk state. Barring some obvious\n> problem like a hard crash, you have to do the work of assessing if the\n> code is correct based on the actual assumptions/context of the code. A\n> static analysis tool is of very little use if you're not going to put\n> the work in.\n\nI'm sure that all these problems will be solved in the future. But how many\nothers will be added.\nI have realized that maybe, it may be hindering the development course, so\nI decided to stop.\n\nI went to a lot of trouble to clearly document the code\n> in question here (the heap TID stuff in _bt_truncate()) -- did you\n> even bother to read those comments once?\n>\nYes, I read.\nMaybe in this specific case, only this, it would solve for the code and the\nstatic analysis tool, but it's just a thought.\n\npivotheaptid = (ItemPointer) ((char *) tidpivot + IndexTupleSize(tidpivot) -\n sizeof(ItemPointerData));\n\nAnyway, thanks for all the answers.\n\nRanier Vilela\n\nEm qua., 2 de set. de 2020 às 20:17, Peter Geoghegan <pg@bowt.ie> escreveu:On Wed, Sep 2, 2020 at 3:16 PM Ranier Vilela <ranier.vf@gmail.com> wrote: \nPerhaps you recall our discussion of a similar false positive in\nnbtsplitloc.c; that had a similar feel to it. For example, if your\nstatic analysis tool says that code that has been around for many\nyears is riddled with bugs, then the problem is almost certainly with\nthe tool (or with how the tool has been used).\nI'm using about 4 static analysis tools.Only one of them has a report of 67690 pages. Assuming an optimistic trend, only 1% could be real failures.It would have 670 real flaws in the entire code.In addition, if the code is compiled with -Wextra, hundreds of type mismatch alerts will be reported, especially comparison between int (signed) and unsigned types.If you try to leaks, you will find this:== 42483 == ERROR: LeakSanitizer: detected memory leaksDirect leak of 576 byte (s) in 1 object (s) allocated from:    # 0 0x7f3204fb7bc8 in malloc (/lib/x86_64-linux-gnu/libasan.so.5+0x10dbc8)    # 1 0x561c58d5b766 in save_ps_display_args /usr/src/postgres/src/backend/utils/misc/ps_status.c:178    # 2 0x561c584a90b3 in main /usr/src/postgres/src/backend/main/main.c:89    # 3 0x7f3204b7f0b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)Indirect leak of 14 byte (s) in 1 object (s) allocated from:    # 0 0x7f3204f403dd in strdup (/lib/x86_64-linux-gnu/libasan.so.5+0x963dd)    # 1 0x561c58d5b817 in save_ps_display_args /usr/src/postgres/src/backend/utils/misc/ps_status.c:186    # 2 0x561c584a90b3 in main /usr/src/postgres/src/backend/main/main.c:89    # 3 0x7f3204b7f0b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)For each reported failure, I have analyzed the code, without focusing on the \"intention of the code\", but trying to abstract and concentrate on following the flow of the variables to make sure that the alert is invalid.Maybe I didn't realize it, but I'm not \"getting out of my head\", these alerts.\n \n\nHigh performance C code very often relies on representational\ninvariants that may not be readily apparent to a compiler --\nespecially when dealing with on-disk state. Barring some obvious\nproblem like a hard crash, you have to do the work of assessing if the\ncode is correct based on the actual assumptions/context of the code. A\nstatic analysis tool is of very little use if you're not going to put\nthe work in. I'm sure that all these problems will be solved in the future. But how many others will be added.I have realized that maybe, it may be hindering the development course, so I decided to stop. I went to a lot of trouble to clearly document the code\nin question here (the heap TID stuff in _bt_truncate()) -- did you\neven bother to read those comments once?Yes, I read.Maybe in this specific case, only this, it would solve for the code and the static analysis tool, but it's just a thought.\tpivotheaptid = (ItemPointer) ((char *) tidpivot + IndexTupleSize(tidpivot) -\t\t\t\t\t\t\t\t  sizeof(ItemPointerData));Anyway, thanks for all the answers.Ranier Vilela", "msg_date": "Thu, 3 Sep 2020 11:39:57 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Re: [NBTREE] Possible NULL pointer dereference\n (backend/access/nbtree/nbutils.c)" }, { "msg_contents": "On Thu, Sep 03, 2020 at 11:39:57AM -0300, Ranier Vilela wrote:\n> I'm using about 4 static analysis tools.\n\nIt seems to me that this is the root of the problem here.\n--\nMichael", "msg_date": "Fri, 4 Sep 2020 10:25:22 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [NBTREE] Possible NULL pointer dereference\n (backend/access/nbtree/nbutils.c)" } ]
[ { "msg_contents": "Hi all,\n\nFor a couple of things I looked at lately, it would be really useful\nto make index_state_set_flags() transactional and replace its use of\nheap_inplace_update() by CatalogTupleUpdate():\n- When dropping an index used in a replica identity, we could make the\nreset of relreplident for the parent table consistent with the moment\nthe index is marked as invalid:\nhttps://www.postgresql.org/message-id/20200831062304.GA6555@paquier.xyz\n- In order to make CREATE INDEX CONCURRENTLY work for partitioned\ntables, we need to be able to switch indisvalid for all the index\npartitions in one final transaction so as we have a consistent\npartition tree at any state of the operation. Obviously,\nheap_inplace_update() is a problem here.\n\nThe restriction we have in place now can be lifted thanks to 813fb03,\nthat removed SnapshotNow, and as far as I looked at the code paths\ndoing scans of pg_index, I don't see any reasons why we could not make\nthis stuff transactional. Perhaps that's just because nobody had use\ncases where it would be useful, and I have two of them lately. Note\nthat 3c84046 was the original commit that introduced the use of\nheap_inplace_update() and index_state_set_flags(), but we don't have\nSnapshotNow anymore. Note as well that we already make the index\nswapping transactional in REINDEX CONCURRENTLY for the pg_index\nentries.\n\nI got the feeling that this is an issue different than the other\nthreads where this was discussed, which is why I am beginning a new\nthread. Any thoughts? Attached is a proposal of patch.\n\nThanks,\n--\nMichael", "msg_date": "Thu, 3 Sep 2020 17:04:40 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Making index_set_state_flags() transactional" }, { "msg_contents": "On 03.09.2020 11:04, Michael Paquier wrote:\n> Hi all,\n>\n> For a couple of things I looked at lately, it would be really useful\n> to make index_state_set_flags() transactional and replace its use of\n> heap_inplace_update() by CatalogTupleUpdate():\n> - When dropping an index used in a replica identity, we could make the\n> reset of relreplident for the parent table consistent with the moment\n> the index is marked as invalid:\n> https://www.postgresql.org/message-id/20200831062304.GA6555@paquier.xyz\n> - In order to make CREATE INDEX CONCURRENTLY work for partitioned\n> tables, we need to be able to switch indisvalid for all the index\n> partitions in one final transaction so as we have a consistent\n> partition tree at any state of the operation. Obviously,\n> heap_inplace_update() is a problem here.\n>\n> The restriction we have in place now can be lifted thanks to 813fb03,\n> that removed SnapshotNow, and as far as I looked at the code paths\n> doing scans of pg_index, I don't see any reasons why we could not make\n> this stuff transactional. Perhaps that's just because nobody had use\n> cases where it would be useful, and I have two of them lately. Note\n> that 3c84046 was the original commit that introduced the use of\n> heap_inplace_update() and index_state_set_flags(), but we don't have\n> SnapshotNow anymore. Note as well that we already make the index\n> swapping transactional in REINDEX CONCURRENTLY for the pg_index\n> entries.\n>\n> I got the feeling that this is an issue different than the other\n> threads where this was discussed, which is why I am beginning a new\n> thread. Any thoughts? Attached is a proposal of patch.\n>\n> Thanks,\n> --\n> Michael\n>\nAs this patch is needed to continue the work started in \n\"reindex/cic/cluster of partitioned tables\" thread, I took a look on it.\n\nI agree that transactional update in index_set_state_flags() is good for \nboth cases, that you mentioned and don't see any restrictions. It seems \nthat not doing this before was just a loose end, as the comment from \n813fb03 patch clearly stated, that it is safe to make this update \ntransactional.\n\nThe patch itself looks clear and committable.\n\n-- \nAnastasia Lubennikova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Fri, 11 Sep 2020 18:42:09 +0300", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Making index_set_state_flags() transactional" }, { "msg_contents": "On Fri, Sep 11, 2020 at 06:42:09PM +0300, Anastasia Lubennikova wrote:\n> I agree that transactional update in index_set_state_flags() is good for\n> both cases, that you mentioned and don't see any restrictions. It seems that\n> not doing this before was just a loose end, as the comment from 813fb03\n> patch clearly stated, that it is safe to make this update transactional.\n> \n> The patch itself looks clear and committable.\n\nThanks for double-checking, Anastasia. Committed.\n--\nMichael", "msg_date": "Mon, 14 Sep 2020 13:58:56 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Making index_set_state_flags() transactional" } ]
[ { "msg_contents": "Hi,\n\nStarting a new thread to discuss a bug related to $subject that Hao Wu\nreported on thread titled \"ALTER TABLE .. DETACH PARTITION\nCONCURRENTLY\" [1]. I have been able to reproduce the bug using steps\nthat Hao gave in that email:\n\ncreate table tpart (i int, j int) partition by range(i);\ncreate table tpart_1 (like tpart);\ncreate table tpart_2 (like tpart);\ncreate table tpart_default (like tpart);\nalter table tpart attach partition tpart_1 for values from (0) to (100);\nalter table tpart attach partition tpart_default default;\ninsert into tpart_2 values (110,110), (120,120), (150,150);\n\nSession 1:\n\nbegin;\nalter table tpart attach partition tpart_2 for values from (100) to (200);\n\nSession 2:\n\nbegin;\ninsert into tpart values (110,110), (120,120), (150,150);\n<blocks waiting for the concurrent attach to finish>\n\nSession 1:\n\nend;\n\nSession 2:\n\nselect tableoid::regclass, * from tpart;\nend;\n\nThe select will show that rows inserted by session 2 are inserted into\ntpart_default, whereas after successfully attaching tpart_2, they do\nnot actually belong there.\n\nThe problem is that when session 2 inserts those rows into tpart, it\nonly knows about 2 partitions: tpart_1, tpart_default, of which it\nselects tpart_default to insert those rows into. When tpart_default\nis locked to perform the insert, it waits for session 1 to release the\nlock taken on tpart_default during the attach command. When it is\nunblocked, it proceeds to finish the insert without rechecking the\npartition constraint which would have been updated as result of a new\npartition having been added to the parent.\n\nNote that we don't normally check the partition constraint when\ninserting a row into a partition if the insert occurs via tuple\nrouting, which makes sense for non-default partitions whose partition\nconstraint cannot change due to concurrent activity. But this test\ncase has shown that the assumption is not safe for a default partition\nwhose constraint is a function of other partitions that exist as of\nwhen the insert occurs.\n\nBy the way, if you reverse the order of operations between session 1\nand 2 such that the insert by session 2 occurs first and then the\nattach by session 1, then you will correctly get this error from the\nattach command:\n\nERROR: updated partition constraint for default partition\n\"tpart_default\" would be violated by some row\n\nAttached is a patch to fix things on the insert side.\n\n-- \nAmit Langote\nEnterpriseDB: http://www.enterprisedb.com\n\n\n[1] https://www.postgresql.org/message-id/DM5PR0501MB3910E97A9EDFB4C775CF3D75A42F0%40DM5PR0501MB3910.namprd05.prod.outlook.com", "msg_date": "Thu, 3 Sep 2020 18:50:00 +0900", "msg_from": "Amit Langote <amitlangote09@gmail.com>", "msg_from_op": true, "msg_subject": "default partition and concurrent attach partition" }, { "msg_contents": "On Thu, Sep 3, 2020 at 6:50 PM Amit Langote <amitlangote09@gmail.com> wrote:\n>\n> Hi,\n>\n> Starting a new thread to discuss a bug related to $subject that Hao Wu\n> reported on thread titled \"ALTER TABLE .. DETACH PARTITION\n> CONCURRENTLY\" [1]. I have been able to reproduce the bug using steps\n> that Hao gave in that email:\n>\n> create table tpart (i int, j int) partition by range(i);\n> create table tpart_1 (like tpart);\n> create table tpart_2 (like tpart);\n> create table tpart_default (like tpart);\n> alter table tpart attach partition tpart_1 for values from (0) to (100);\n> alter table tpart attach partition tpart_default default;\n> insert into tpart_2 values (110,110), (120,120), (150,150);\n>\n> Session 1:\n>\n> begin;\n> alter table tpart attach partition tpart_2 for values from (100) to (200);\n>\n> Session 2:\n>\n> begin;\n> insert into tpart values (110,110), (120,120), (150,150);\n> <blocks waiting for the concurrent attach to finish>\n>\n> Session 1:\n>\n> end;\n>\n> Session 2:\n>\n> select tableoid::regclass, * from tpart;\n> end;\n>\n> The select will show that rows inserted by session 2 are inserted into\n> tpart_default, whereas after successfully attaching tpart_2, they do\n> not actually belong there.\n>\n> The problem is that when session 2 inserts those rows into tpart, it\n> only knows about 2 partitions: tpart_1, tpart_default, of which it\n> selects tpart_default to insert those rows into. When tpart_default\n> is locked to perform the insert, it waits for session 1 to release the\n> lock taken on tpart_default during the attach command. When it is\n> unblocked, it proceeds to finish the insert without rechecking the\n> partition constraint which would have been updated as result of a new\n> partition having been added to the parent.\n>\n> Note that we don't normally check the partition constraint when\n> inserting a row into a partition if the insert occurs via tuple\n> routing, which makes sense for non-default partitions whose partition\n> constraint cannot change due to concurrent activity. But this test\n> case has shown that the assumption is not safe for a default partition\n> whose constraint is a function of other partitions that exist as of\n> when the insert occurs.\n>\n> By the way, if you reverse the order of operations between session 1\n> and 2 such that the insert by session 2 occurs first and then the\n> attach by session 1, then you will correctly get this error from the\n> attach command:\n>\n> ERROR: updated partition constraint for default partition\n> \"tpart_default\" would be violated by some row\n>\n> Attached is a patch to fix things on the insert side.\n\nForgot to mention that the problem exists as of v12 (commit: 898e5e329).\n\n-- \nAmit Langote\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 3 Sep 2020 18:56:35 +0900", "msg_from": "Amit Langote <amitlangote09@gmail.com>", "msg_from_op": true, "msg_subject": "Re: default partition and concurrent attach partition" }, { "msg_contents": "Thanks for this fix! Looking into it now.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Thu, 3 Sep 2020 16:36:29 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: default partition and concurrent attach partition" }, { "msg_contents": "On 2020-Sep-03, Alvaro Herrera wrote:\n\n> +\t/*\n> +\t * If setting up a PartitionDispatch for a sub-partitioned table, we may\n> +\t * also need a fake ResultRelInfo for checking the partition constraint\n> +\t * later; set that up now.\n> +\t */\n> +\tif (parent_pd)\n> +\t{\n> +\t\tResultRelInfo *rri = makeNode(ResultRelInfo);\n> +\n> +\t\tInitResultRelInfo(rri, rel, 1, proute->partition_root, 0);\n> +\t\tproute->nonleaf_partitions[dispatchidx] = rri;\n> +\t}\n> +\n\nHeh, I had intended to remove the attachment before sending, because I\nthought I was seeing a problem with this proposed coding of mine. But\nsince I sent it by mistake, I'll explain: I think this will fail if we\nhave a partitioned default partition, and we direct the insert to it\ndirectly while attaching a partition to its parent. I think that kind\nof scenario deserves its own test case.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 3 Sep 2020 17:02:06 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: default partition and concurrent attach partition" }, { "msg_contents": "Also, I should have pointed out that ExecInsert doesn't actually check\nthe partitin constraint except in very specific cases; what it does is\nexpect that the partition routing code got it right. So the comment\nyou're adding about that is wrong, and it did misled me into changing\nyour code in a way that actually caused a bug -- hence my proposed\nrewording.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 3 Sep 2020 17:28:03 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: default partition and concurrent attach partition" }, { "msg_contents": "Hi Alvaro,\n\nOn Fri, Sep 4, 2020 at 6:28 AM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n>\n> Also, I should have pointed out that ExecInsert doesn't actually check\n> the partitin constraint except in very specific cases; what it does is\n> expect that the partition routing code got it right. So the comment\n> you're adding about that is wrong, and it did misled me into changing\n> your code in a way that actually caused a bug -- hence my proposed\n> rewording.\n\nThanks for taking a look.\n\n /*\n * If this partition is the default one, we must check its partition\n- * constraint, because it may have changed due to partitions being\n- * added to the parent concurrently. We do the check here instead of\n- * in ExecInsert(), because we would not want to miss checking the\n- * constraint of any nonleaf partitions as they never make it to\n- * ExecInsert().\n+ * constraint now, which may have changed due to partitions being\n+ * added to the parent concurrently.\n\nI am fine with your rewording but let me explain how I ended up\nwriting what I wrote:\n\nAt first I had pondered tweaking the following code in ExecInsert() to\nfix this bug:\n\n /*\n * Also check the tuple against the partition constraint, if there is\n * one; except that if we got here via tuple-routing, we don't need to\n * if there's no BR trigger defined on the partition.\n */\n if (resultRelInfo->ri_PartitionCheck &&\n (resultRelInfo->ri_PartitionRoot == NULL ||\n (resultRelInfo->ri_TrigDesc &&\n resultRelInfo->ri_TrigDesc->trig_insert_before_row)))\n ExecPartitionCheck(resultRelInfo, slot, estate, true);\n\nI gave up because I concluded that there isn't enough information at\nthis place in code to determine if the partition is a default\npartition, so I moved my attention to ExecFindPartition() where we\nhave access to the parent's PartitionDesc which is enough to do so.\nIn the process of modifying ExecFindPartition() to fix the bug I\nrealized that default partitions can be partitioned and\nsub-partitioned partitions never reach ExecInsert(). So, beside the\nearlier mentioned inconvenience of fixing this bug in ExecInsert(),\nthere is also the problem that such a fix would have missed addressing\nsub-partitioned default partitions. I thought someone beside me would\nalso wonder why ExecInsert() is not touched in this fix, hence the\ncomment.\n\nFWIW, I still prefer \"minimally valid ResultRelInfo\" to \"fake\nResultRelInfo\", because those aren't really fake, are they? They are\nas valid as any other ResultRelInfo as far I can see. I said\n\"minimally valid\" because a fully-valid partition ResultRelInfo is one\nmade by ExecInitPartitionInfo(), which I avoided to use here thinking\nthat would be overkill.\n\n-- \nAmit Langote\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 4 Sep 2020 11:57:33 +0900", "msg_from": "Amit Langote <amitlangote09@gmail.com>", "msg_from_op": true, "msg_subject": "Re: default partition and concurrent attach partition" }, { "msg_contents": "On 2020-Sep-04, Amit Langote wrote:\n\nHello\n\n> FWIW, I still prefer \"minimally valid ResultRelInfo\" to \"fake\n> ResultRelInfo\", because those aren't really fake, are they? They are\n> as valid as any other ResultRelInfo as far I can see. I said\n> \"minimally valid\" because a fully-valid partition ResultRelInfo is one\n> made by ExecInitPartitionInfo(), which I avoided to use here thinking\n> that would be overkill.\n\nWell, they are fake in that the ri_RangeTableIndex they carry is bogus,\nwhich means that ExecBuildSlotValueDescription will misbehave if the\npartitioned default partition has a different column order than its\nparent. That can be evidenced by changing the setup block in the\nisolation test as in the attached; and you'll get an undesirable error\nlike this:\n\n2020-09-07 19:00:49.513 -03 [12981] ERROR: attribute 2 of type record has wrong type\n2020-09-07 19:00:49.513 -03 [12981] DETAIL: Table has type text, but query expects integer.\n2020-09-07 19:00:49.513 -03 [12981] STATEMENT: insert into attach_tab values (110, 'eleven and five twenties');\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Mon, 7 Sep 2020 19:05:41 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: default partition and concurrent attach partition" }, { "msg_contents": "On 2020-Sep-07, Alvaro Herrera wrote:\n\n> Well, they are fake in that the ri_RangeTableIndex they carry is bogus,\n> which means that ExecBuildSlotValueDescription will misbehave if the\n> partitioned default partition has a different column order than its\n> parent. That can be evidenced by changing the setup block in the\n> isolation test as in the attached; and you'll get an undesirable error\n> like this:\n> \n> 2020-09-07 19:00:49.513 -03 [12981] ERROR: attribute 2 of type record has wrong type\n> 2020-09-07 19:00:49.513 -03 [12981] DETAIL: Table has type text, but query expects integer.\n> 2020-09-07 19:00:49.513 -03 [12981] STATEMENT: insert into attach_tab values (110, 'eleven and five twenties');\n\n... and I sent before completing. I'm not sure what a good fix for this\nis. We could try to initialize the resultRelInfo honestly, or we could\nset ri_RangeTableIndex to some invalid value that will ... eh ... do\nsomething else.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 7 Sep 2020 19:10:07 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: default partition and concurrent attach partition" }, { "msg_contents": "Ah, it looks like we can get away with initializing the RRI to 0, and\nthen explicitly handle that case in ExecPartitionCheckEmitError, as in\nthe attached (which means reindenting, but I left it alone to make it\neasy to read). It kinda sucks because we don't report the tuple that\ncauses the error, but\n\na) it's a very unlikely case anyway\nb) it's better than the bogus error message\nc) it's better than some hypothetical crash\nd) nobody uses partitioned default partitions anyway\ne) nobody uses differing column order anyway\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Mon, 7 Sep 2020 19:35:45 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: default partition and concurrent attach partition" }, { "msg_contents": "On 2020-Sep-07, Alvaro Herrera wrote:\n\n> Ah, it looks like we can get away with initializing the RRI to 0, and\n> then explicitly handle that case in ExecPartitionCheckEmitError, as in\n> the attached (which means reindenting, but I left it alone to make it\n> easy to read).\n\nWell, that was silly -- this seems fixable by mapping the tuple columns\nprior to ExecPartitionCheck, which is achievable with something like\n\n\t\tif (partidx == partdesc->boundinfo->default_index)\n\t\t{\n\t\t\tTupleTableSlot *tempslot;\n\n\t\t\tif (dispatch->tupmap != NULL)\n\t\t\t{\n\t\t\t\ttempslot = MakeSingleTupleTableSlot(RelationGetDescr(rri->ri_RelationDesc),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &TTSOpsHeapTuple);\n\t\t\t\ttempslot = execute_attr_map_slot(dispatch->tupmap, slot, tempslot);\n\t\t\t}\n\t\t\telse\n\t\t\t\ttempslot = slot;\n\t\t\tExecPartitionCheck(rri, tempslot, estate, true);\n\t\t\tif (dispatch->tupmap != NULL)\n\t\t\t\tExecDropSingleTupleTableSlot(tempslot);\n\t\t}\n\nthough this exact incantation, apart from being pretty horrible, doesn't\nactually work (other than to fix this specific test case -- it crashes\nelsewhere.)\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 7 Sep 2020 20:44:27 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: default partition and concurrent attach partition" }, { "msg_contents": "Hi Alvaro,\n\nOn Tue, Sep 8, 2020 at 8:44 AM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n> On 2020-Sep-07, Alvaro Herrera wrote:\n>\n> > Ah, it looks like we can get away with initializing the RRI to 0, and\n> > then explicitly handle that case in ExecPartitionCheckEmitError, as in\n> > the attached (which means reindenting, but I left it alone to make it\n> > easy to read).\n\nAt this point, I think it may be clear that ri_RangeTableIndex being\nset to a dummy value isn't problematic. I checked the code paths you\nmentioned upthread, but don't see anything that would be broken by\nri_RangeTableIndex being set to a dummy value of 1.\n\nMoving on from that...\n\n> Well, that was silly -- this seems fixable by mapping the tuple columns\n> prior to ExecPartitionCheck, which is achievable with something like\n>\n> if (partidx == partdesc->boundinfo->default_index)\n> {\n> TupleTableSlot *tempslot;\n>\n> if (dispatch->tupmap != NULL)\n> {\n> tempslot = MakeSingleTupleTableSlot(RelationGetDescr(rri->ri_RelationDesc),\n> &TTSOpsHeapTuple);\n> tempslot = execute_attr_map_slot(dispatch->tupmap, slot, tempslot);\n> }\n> else\n> tempslot = slot;\n> ExecPartitionCheck(rri, tempslot, estate, true);\n> if (dispatch->tupmap != NULL)\n> ExecDropSingleTupleTableSlot(tempslot);\n> }\n>\n> though this exact incantation, apart from being pretty horrible, doesn't\n> actually work (other than to fix this specific test case -- it crashes\n> elsewhere.)\n\nYeah, we need to make sure that ExecPartitionCheck gets a slot whose\nTupleDesc matches the partition's. Actually we do have such dedicated\nslots for partitions around (for both sub-partitioned and leaf\npartitions), so we can simply use them instead of creating one from\nscratch for every use. It did take some code rearrangement to\nactually make that work though.\n\nAttached is the latest patch including those changes. Also, I have\nmerged your earlier \"fixes\" patch and updated the isolation test to\nexercise a case with sub-partitioned default partition, as well as\nvarying attribute numbers. Patch applies as-is to both HEAD and v13\nbranches, but needs slight changes to apply to v12 branch, so also\nattaching one for that branch.\n\n\n\n--\nAmit Langote\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Tue, 8 Sep 2020 16:27:35 +0900", "msg_from": "Amit Langote <amitlangote09@gmail.com>", "msg_from_op": true, "msg_subject": "Re: default partition and concurrent attach partition" }, { "msg_contents": "Hello Amit,\n\nOn 2020-Sep-08, Amit Langote wrote:\n\n> On Tue, Sep 8, 2020 at 8:44 AM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n> > On 2020-Sep-07, Alvaro Herrera wrote:\n> >\n> > > Ah, it looks like we can get away with initializing the RRI to 0, and\n> > > then explicitly handle that case in ExecPartitionCheckEmitError, as in\n> > > the attached (which means reindenting, but I left it alone to make it\n> > > easy to read).\n> \n> At this point, I think it may be clear that ri_RangeTableIndex being\n> set to a dummy value isn't problematic.\n\nYep ... I misled myself.\n\n> Yeah, we need to make sure that ExecPartitionCheck gets a slot whose\n> TupleDesc matches the partition's. Actually we do have such dedicated\n> slots for partitions around (for both sub-partitioned and leaf\n> partitions),\n\nYeah, that's what I was looking for.\n\n> so we can simply use them instead of creating one from\n> scratch for every use. It did take some code rearrangement to\n> actually make that work though.\n\nThanks. It doesn't look too bad ... I'd say it even looks easier to\nread now in terms of code structure.\n\n> Attached is the latest patch including those changes. Also, I have\n> merged your earlier \"fixes\" patch and updated the isolation test to\n> exercise a case with sub-partitioned default partition, as well as\n> varying attribute numbers. Patch applies as-is to both HEAD and v13\n> branches, but needs slight changes to apply to v12 branch, so also\n> attaching one for that branch.\n\nThanks, will dispatch it shortly.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 8 Sep 2020 11:18:16 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: default partition and concurrent attach partition" }, { "msg_contents": "Hi,\n\nAndres added to CC because of TTS interface: apparently calling\nslot_getallattrs() on a virtual slot raises error that \"getsomeattrs is\nnot required to be called on a virtual tuple table slot\". I'm thinking\nthat this exposes implementation details that should not be necessary\nfor a caller to know; patch 0001 fixes that at the problematic caller by\nmaking the slot_getallatrs() call conditional on the slot not being\nvirtual, but I wonder if the better fix isn't to remove the elog(ERROR)\nat tts_virtual_getsomeattrs.\n\nMoving on from that -- this is a version of Amit's previous patch that I\nlike better. I think the \"prev_myslot\" thing was a bit ugly, but it\nturns out that with the above fix we can clear the slot before creating\nthe new one, making things more sensible. I also changed the \"do {}\nwhile ()\" into a simple \"while {}\" loop, which is sensible since the\ncondition is true on loop entrance. Minor comment rewording also.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Tue, 8 Sep 2020 17:17:52 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: default partition and concurrent attach partition" }, { "msg_contents": "On 2020-Sep-08, Alvaro Herrera wrote:\n\n> Andres added to CC because of TTS interface: apparently calling\n> slot_getallattrs() on a virtual slot raises error that \"getsomeattrs is\n> not required to be called on a virtual tuple table slot\". I'm thinking\n> that this exposes implementation details that should not be necessary\n> for a caller to know; patch 0001 fixes that at the problematic caller by\n> making the slot_getallatrs() call conditional on the slot not being\n> virtual, but I wonder if the better fix isn't to remove the elog(ERROR)\n> at tts_virtual_getsomeattrs.\n\nActually I misread the code, so this is all bogus. Nevermind ...\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 8 Sep 2020 19:13:30 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: default partition and concurrent attach partition" }, { "msg_contents": "On 2020-Sep-08, Amit Langote wrote:\n\n> Yeah, we need to make sure that ExecPartitionCheck gets a slot whose\n> TupleDesc matches the partition's. Actually we do have such dedicated\n> slots for partitions around (for both sub-partitioned and leaf\n> partitions), so we can simply use them instead of creating one from\n> scratch for every use. It did take some code rearrangement to\n> actually make that work though.\n\nPushed, thanks for working on this fix.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 8 Sep 2020 19:41:42 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: default partition and concurrent attach partition" }, { "msg_contents": "On Wed, Sep 9, 2020 at 7:41 AM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n> On 2020-Sep-08, Amit Langote wrote:\n>\n> > Yeah, we need to make sure that ExecPartitionCheck gets a slot whose\n> > TupleDesc matches the partition's. Actually we do have such dedicated\n> > slots for partitions around (for both sub-partitioned and leaf\n> > partitions), so we can simply use them instead of creating one from\n> > scratch for every use. It did take some code rearrangement to\n> > actually make that work though.\n>\n> Pushed, thanks for working on this fix.\n\nThanks.\n\n-- \nAmit Langote\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 9 Sep 2020 10:20:03 +0900", "msg_from": "Amit Langote <amitlangote09@gmail.com>", "msg_from_op": true, "msg_subject": "Re: default partition and concurrent attach partition" } ]
[ { "msg_contents": "Hi folks\n\nThe attached patch series adds support for detecting coding errors where a\nstack-allocated ErrorContextCallback is not popped from the\nerror_context_stack before the variable leaves scope.\n\nWith the attached patches this code will emit a backtrace and abort() on\ncassert builds at the \"return\" statement where it leaks the stack pointer:\n\n ErrorContextCallback cb pg_errcontext_check();\n ...\n cb.previous = error_context_stack;\n error_context_stack = &cb;\n ...\n if (something)\n return; /* whoops! */\n ...\n error_context_stack = error_context_stack->previous;\n\nas I discuss on this old blog article here:\nhttps://www.2ndquadrant.com/en/blog/dev-corner-error-context-stack-corruption/\n\nNote the pgl_errcontext_check() in the above, which enables the check.\n\nThe infrastructure added by the patch could well be useful for other\nsimilar validation steps. In fact, I've added a similar validator that\ndetects escapes from PG_TRY() blocks, so you get a neat assertion failure\nat the point of escape instead of a crash at a __longjmp() with a\nnonsensical stack. Example using a deliberately introduced mistake in\npostgres_fdw as a test:\n\nWithout the PG_TRY() patch:\n\n#0 __longjmp () at ../sysdeps/x86_64/__longjmp.S:111\n#1 0xc35a5d9e1a902cfc in ?? ()\nBacktrace stopped: Cannot access memory at address 0xc0ea5d9e1a902cfc\n\nWith the PG_TRY() patch (abbreviated):\n\n#3 0x0000000000abbd4b in pg_try_check_return_guard\n#4 0x00007f8e2e20e41a in fetch_more_data\n#5 0x00007f8e2e20a80a in postgresIterateForeignScan\n...\n\nNote that valgrind's memcheck, gcc's -fstack-protector, etc are all quite\nbad at detecting this class of error, so being able to do so automatically\nshould be nice. I've had an interesting time chasing down error context\nstack mistakes a few times in the past\n\nWe unfortunately cannot use it for RAII-style coding because the underlying\n__attribute__((callback(..))) is not available on MSVC. As usual. But it\nremains useful for checking and assertions.\n\nThe patch is supplied as a small series:\n\n(1) Add some documentation on error context callback usage\n(2) Add pg_errcontext_check() to detect ErrorContextCallback escapes\n(3) Enable pg_errcontext_check() for all in-tree users\n(4) Document that generally PG_CATCH() should PG_RE_THROW()\n(5) Assert() if returning from inside a PG_TRY() / PG_CATCH() block\n(6) [RFC] Add a more succinct API for error context stack callbacks\n(7) [RFC] Use __has_attribute for compiler attribute detection where\npossible\n\nI also added a patch (6) on top as a RFC of sorts, which adds a more\nsuccinct API for error context setup and teardown. It's not required for\nthese changes, but it might make sense to adopt it at the same time if\nwe're changing usage across the tree anyway.\n\nA further patch (7) switches over to using __has_attribute instead of\nexplicit compiler version checks. Again, optional, more of a RFC.\n\n-- \n Craig Ringer http://www.2ndQuadrant.com/\n 2ndQuadrant - PostgreSQL Solutions for the Enterprise", "msg_date": "Thu, 3 Sep 2020 19:21:59 +0800", "msg_from": "Craig Ringer <craig@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "[PATCH] Detect escape of ErrorContextCallback stack pointers (and\n from PG_TRY() )" }, { "msg_contents": "Craig Ringer <craig@2ndquadrant.com> writes:\n> The attached patch series adds support for detecting coding errors where a\n> stack-allocated ErrorContextCallback is not popped from the\n> error_context_stack before the variable leaves scope.\n\nSo my immediate thoughts about this are\n\n(1) It's mighty invasive for what it accomplishes. AFAIK we have\nhad few of this class of bug, and so I'm not excited about touching\nevery callback use in the tree to add defenses. It's also not great\nthat future code additions won't be protected unless they remember\nto add these magic annotations. The PG_TRY application is better since\nit's wrapped into the existing macro.\n\n(2) I don't like that this is adding runtime overhead to try to detect\nsuch bugs.\n\n(3) I think it's a complete failure that such a bug will only be\ndetected if the faulty code path is actually taken. I think it's\nquite likely that any such bugs that are lurking are in \"can't\nhappen\", or at least hard-to-hit, corner cases --- if they were in\nroutinely tested paths, we'd have noticed them by now. So it'd be far\nmore helpful if we had a static-analysis way to detect such issues.\n\nThinking about (3), I wonder whether there's a way to instruct Coverity\nto detect such errors.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 03 Sep 2020 10:28:08 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Detect escape of ErrorContextCallback stack pointers (and\n from PG_TRY() )" }, { "msg_contents": "On Thu, 3 Sep 2020 at 22:28, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Craig Ringer <craig@2ndquadrant.com> writes:\n> > The attached patch series adds support for detecting coding errors where\n> a\n> > stack-allocated ErrorContextCallback is not popped from the\n> > error_context_stack before the variable leaves scope.\n>\n> So my immediate thoughts about this are\n>\n> (1) It's mighty invasive for what it accomplishes. AFAIK we have\n> had few of this class of bug, and so I'm not excited about touching\n> every callback use in the tree to add defenses. It's also not great\n> that future code additions won't be protected unless they remember\n> to add these magic annotations. The PG_TRY application is better since\n> it's wrapped into the existing macro.\n>\n\nI agree with you there. I'd actually like to change how we set up\nerrcontext callbacks anyway, as I think they're ugly, verbose and\nerror-prone.\n\nSee patch 6 for a RFC on that.\n\nWith regards to PG_TRY() you may note that patch 5 adds a similar check to\ndetect escapes from PG_TRY() / PG_CATCH() bodies.\n\n(2) I don't like that this is adding runtime overhead to try to detect\n> such bugs.\n>\n\nRight. Only in cassert builds, though.\n\nFrankly I'd be happy enough even having it as something I can turn on when\nI wanted it. I've had a heck of a time tracking down errcontext escapes in\nthe past. I wrote it for an extension, then figured I'd submit it to core\nand see if anyone wanted it.\n\nEven if we don't adopt it in PostgreSQL, now it's out there to help out\nothers debugging similar issues.\n\n(3) I think it's a complete failure that such a bug will only be\n> detected if the faulty code path is actually taken. I think it's\n> quite likely that any such bugs that are lurking are in \"can't\n> happen\", or at least hard-to-hit, corner cases --- if they were in\n> routinely tested paths, we'd have noticed them by now. So it'd be far\n> more helpful if we had a static-analysis way to detect such issues.\n>\n> Thinking about (3), I wonder whether there's a way to instruct Coverity\n> to detect such errors.\n>\n\nI think calling it a \"complete failure\" is ridiculous. By the same\nrationale, we shouldn't bother with Assert(...) at all. But I agree that\nit's definitely far from as good as having a statically verifiable check\nwould be, and this *should* be something we can statically verify.\n\nI actually had a pretty good look around for static analysis options to see\nif I could find anything that might help us out before I landed up with\nthis approach.\n\nThe sticking point is the API we use. By using auto stack variables (and\ndoing so in pure C where they cannot have destructors) and using direct\nassignments to globals, we cannot use the majority of static analysis\nannotations since they tend to be aimed at function-based APIs. And for\nsome reason most static analysis tools appear to be poor at discovering\nescapes of pointers to stack variables leaving scope, at least unless you\nuse annotated functions that record ownership transfers. Which we can't\nbecause ... direct assignment.\n\nIt's one of the reasons I want to wrap the errcontext API per patch 6 in\nthe above series. The current API is extremely verbose, hard to validate\nand check, and difficult to apply static analysis to.\n\nIf we had error context setup/teardown macros we could implement them using\nstatic inline functions and annotate them as appropriate for the target\ntoolchain and available static analysis tools.\n\nSo what do you think of patch 6?\n\nI'll try tweaking the updated API to add annotateable functions and see if\nthat helps static analysis tools detect issues, then report back.\n\nI personally think it'd be well worth adopting a wrapped API and\nsimultaneously renaming ErrorContextCallback to ErrorContextCallbackData to\nensure that code must be updated to compile with the changes. It'd be\nsimple to provide a backwards compatibility header that extension authors\ncan copy into their trees so they can use the new API when building against\nold postgres, greatly reducing the impact on extension authors. (We do that\nsort of thing constantly in pglogical and BDR).\n\n-- \n Craig Ringer http://www.2ndQuadrant.com/\n 2ndQuadrant - PostgreSQL Solutions for the Enterprise\n\nOn Thu, 3 Sep 2020 at 22:28, Tom Lane <tgl@sss.pgh.pa.us> wrote:Craig Ringer <craig@2ndquadrant.com> writes:\n> The attached patch series adds support for detecting coding errors where a\n> stack-allocated ErrorContextCallback is not popped from the\n> error_context_stack before the variable leaves scope.\n\nSo my immediate thoughts about this are\n\n(1) It's mighty invasive for what it accomplishes.  AFAIK we have\nhad few of this class of bug, and so I'm not excited about touching\nevery callback use in the tree to add defenses.  It's also not great\nthat future code additions won't be protected unless they remember\nto add these magic annotations.  The PG_TRY application is better since\nit's wrapped into the existing macro.I agree with you there. I'd actually like to change how we set up errcontext callbacks anyway, as I think they're ugly, verbose and error-prone.See patch 6 for a RFC on that.With regards to PG_TRY() you may note that patch 5 adds a similar check to detect escapes from PG_TRY() / PG_CATCH() bodies.\n\n(2) I don't like that this is adding runtime overhead to try to detect\nsuch bugs.Right. Only in cassert builds, though.Frankly I'd be happy enough even having it as something I can turn on when I wanted it. I've had a heck of a time tracking down errcontext escapes in the past. I wrote it for an extension, then figured I'd submit it to core and see if anyone wanted it.Even if we don't adopt it in PostgreSQL, now it's out there to help out others debugging similar issues. \n\n(3) I think it's a complete failure that such a bug will only be\ndetected if the faulty code path is actually taken.  I think it's\nquite likely that any such bugs that are lurking are in \"can't\nhappen\", or at least hard-to-hit, corner cases --- if they were in\nroutinely tested paths, we'd have noticed them by now.  So it'd be far\nmore helpful if we had a static-analysis way to detect such issues.\n\nThinking about (3), I wonder whether there's a way to instruct Coverity\nto detect such errors.I think calling it a \"complete failure\" is ridiculous. By the same rationale, we shouldn't bother with Assert(...) at all. But I agree that it's definitely far from as good as having a statically verifiable check would be, and this *should* be something we can statically verify.I actually had a pretty good look around for static analysis options to see if I could find anything that might help us out before I landed up with this approach.The sticking point is the API we use. By using auto stack variables (and doing so in pure C where they cannot have destructors) and using direct assignments to globals, we cannot use the majority of static analysis annotations since they tend to be aimed at function-based APIs. And for some reason most static analysis tools appear to be poor at discovering escapes of pointers to stack variables leaving scope, at least unless you use annotated functions that record ownership transfers. Which we can't because ... direct assignment.It's one of the reasons I want to wrap the errcontext API per patch 6 in the above series. The current API is extremely verbose, hard to validate and check, and difficult to apply static analysis to.If we had error context setup/teardown macros we could implement them using static inline functions and annotate them as appropriate for the target toolchain and available static analysis tools.So what do you think of patch 6?I'll try tweaking the updated API to add annotateable functions and see if that helps static analysis tools detect issues, then report back.I personally think it'd be well worth adopting a wrapped API and simultaneously renaming ErrorContextCallback to ErrorContextCallbackData to ensure that code must be updated to compile with the changes. It'd be simple to provide a backwards compatibility header that extension authors can copy into their trees so they can use the new API when building against old postgres, greatly reducing the impact on extension authors. (We do that sort of thing constantly in pglogical and BDR).--  Craig Ringer                   http://www.2ndQuadrant.com/ 2ndQuadrant - PostgreSQL Solutions for the Enterprise", "msg_date": "Fri, 4 Sep 2020 14:13:23 +0800", "msg_from": "Craig Ringer <craig@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: [PATCH] Detect escape of ErrorContextCallback stack pointers (and\n from PG_TRY() )" }, { "msg_contents": "On Fri, 4 Sep 2020 at 14:13, Craig Ringer <craig@2ndquadrant.com> wrote:\n\n>\n> I actually had a pretty good look around for static analysis options to\n> see if I could find anything that might help us out before I landed up with\n> this approach.\n>\n\nApparently not good enough.\n\nhttps://clang.llvm.org/docs/analyzer/checkers.html#core-stackaddressescape-c\n\nUsing a test program:\n\nreturn_stack_escape.c:14:3: warning: Address of stack memory associated\nwith local variable 'g' is still referred to by the global variable\n'guard_ptr' upon returning to the caller. This will be a dangling reference\n return do_fail;\n ^~~~~~~~~~~~~~\n1 warning generated.\n\nso ... that's interesting. I'll need to do some checking and verify that\nit's effective on the actual problem I originally had, but if so, I shall\nproceed with kicking myself now.\n\nHandily, the same thing can be used to detect PG_TRY() escapes.\n\n-- \n Craig Ringer http://www.2ndQuadrant.com/\n 2ndQuadrant - PostgreSQL Solutions for the Enterprise\n\nOn Fri, 4 Sep 2020 at 14:13, Craig Ringer <craig@2ndquadrant.com> wrote:I actually had a pretty good look around for static analysis options to see if I could find anything that might help us out before I landed up with this approach.Apparently not good enough.https://clang.llvm.org/docs/analyzer/checkers.html#core-stackaddressescape-cUsing a test program:return_stack_escape.c:14:3: warning: Address of stack memory associated with local variable 'g' is still referred to by the global variable 'guard_ptr' upon returning to the caller.  This will be a dangling reference                return do_fail;                ^~~~~~~~~~~~~~1 warning generated.so ... that's interesting. I'll need to do some checking and verify that it's effective on the actual problem I originally had, but if so, I shall proceed with kicking myself now.Handily, the same thing can be used to detect PG_TRY() escapes.--  Craig Ringer                   http://www.2ndQuadrant.com/ 2ndQuadrant - PostgreSQL Solutions for the Enterprise", "msg_date": "Fri, 4 Sep 2020 14:55:01 +0800", "msg_from": "Craig Ringer <craig@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: [PATCH] Detect escape of ErrorContextCallback stack pointers (and\n from PG_TRY() )" }, { "msg_contents": "On Fri, 4 Sep 2020 at 14:55, Craig Ringer <craig@2ndquadrant.com> wrote:\n\n\n> Using a test program:\n>\n> return_stack_escape.c:14:3: warning: Address of stack memory associated\n> with local variable 'g' is still referred to by the global variable\n> 'guard_ptr' upon returning to the caller. This will be a dangling reference\n> return do_fail;\n> ^~~~~~~~~~~~~~\n> 1 warning generated.\n>\n>\nExample here:\n\nhttps://github.com/ringerc/scrapcode/tree/master/c/clang_return_stack_checks\n\nSo I find that actually, the __attribute__((callback(fn)) approach is\nunnecessary for the purpose proposed.\n\n\n\nI still think we should be looking at tidying up the error contexts API,\nbut it's easy enough for extensions to provide a wrapper over it, so that's\nnot a big deal really.\n\nI will submit my docs patches separately to ensure they get some attention,\nand I'll experiment with llvm threadsafety annotations / capabilities.\n\n\n\n\n-- \n Craig Ringer http://www.2ndQuadrant.com/\n 2ndQuadrant - PostgreSQL Solutions for the Enterprise\n\nOn Fri, 4 Sep 2020 at 14:55, Craig Ringer <craig@2ndquadrant.com> wrote: Using a test program:return_stack_escape.c:14:3: warning: Address of stack memory associated with local variable 'g' is still referred to by the global variable 'guard_ptr' upon returning to the caller.  This will be a dangling reference                return do_fail;                ^~~~~~~~~~~~~~1 warning generated.Example here:https://github.com/ringerc/scrapcode/tree/master/c/clang_return_stack_checksSo I find that actually, the __attribute__((callback(fn)) approach is unnecessary for the purpose proposed.I still think we should be looking at tidying up the error contexts API, but it's easy enough for extensions to provide a wrapper over it, so that's not a big deal really.I will submit my docs patches separately to ensure they get some attention, and I'll experiment with llvm threadsafety annotations / capabilities. --  Craig Ringer                   http://www.2ndQuadrant.com/ 2ndQuadrant - PostgreSQL Solutions for the Enterprise", "msg_date": "Tue, 8 Sep 2020 10:27:11 +0800", "msg_from": "Craig Ringer <craig@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: [PATCH] Detect escape of ErrorContextCallback stack pointers (and\n from PG_TRY() )" }, { "msg_contents": "Craig Ringer <craig@2ndquadrant.com> writes:\n> Example here:\n> https://github.com/ringerc/scrapcode/tree/master/c/clang_return_stack_checks\n> So I find that actually, the __attribute__((callback(fn)) approach is\n> unnecessary for the purpose proposed.\n\nI tested this by injecting some faults of the described sort.\n\ndiff --git a/src/backend/commands/copy.c b/src/backend/commands/copy.c\nindex db7d24a511..eaf7716816 100644\n--- a/src/backend/commands/copy.c\n+++ b/src/backend/commands/copy.c\n@@ -3025,6 +3025,8 @@ CopyFrom(CopyState cstate)\n \n myslot = CopyMultiInsertInfoNextFreeSlot(&multiInsertInfo,\n resultRelInfo);\n+ if (!myslot)\n+ return 0;\n }\n \n /*\n\nleads to\n\n/home/tgl/pgsql/src/backend/commands/copy.c:3029:6: warning: Address of stack memory associated with local variable 'errcallback' is still referred to by the global variable 'error_context_stack' upon returning to the caller. This will be a dangling reference\n return 0;\n ^~~~~~~~\n\nSo that's good. However, a similar experiment with returning from inside\na PG_TRY does *not* produce a warning. I suspect maybe the compiler\nthrows up its hands when it sees sigsetjmp?\n\n(These results from clang 10.0.0 on Fedora 32.)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 07 Sep 2020 22:56:03 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Detect escape of ErrorContextCallback stack pointers (and\n from PG_TRY() )" }, { "msg_contents": "On Tue, 8 Sep 2020 at 10:56, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n>\n> So that's good. However, a similar experiment with returning from inside\n> a PG_TRY does *not* produce a warning. I suspect maybe the compiler\n> throws up its hands when it sees sigsetjmp?\n>\n\nI find that odd myself, given that in PG_TRY() we:\n\n PG_exception_stack = &_local_sigjmp_buf;\n\nand a return within that block should count as a pointer to\n_local_sigjmp_buf escaping. Yet I confirm that I don't get a warning on\nclang-analyzer 10.0.0 (fedora 32) in my builds either. Even with -O0.\n\nTL;DR:\n-------\n\nIt's not due to sigsetjmp() at all though; see\nhttps://github.com/ringerc/scrapcode/blob/master/c/clang_return_stack_checks/mask_local_escape.c\nfor part of what's going on.\n\nI haven't worked out why sometimes an unrelated stack escape gets hidden\nthough.\n\nAttached patches demonstrate tests and are DEFINITELY NOT proposals for\ncore!\n\nSUMMARY\n-----\n\nI found per test details below (links and demo patches supplied, patches\nNOT proposed for inclusion in pg) that scan-build seems to be able to track\na local escape via simple indirection such as copying the address to a\nlocal first, but cannot track it when it is assigned to a struct member in\na global pointer if that global pointer is then replaced, even if it's\nrestored immediately.\n\nDemonstration code to illustrate this is at\nhttps://github.com/ringerc/scrapcode/blob/master/c/clang_return_stack_checks/mask_local_escape.c\n\nThis produces no warnings from scan-build but leaks a pointer to an\nauto-variable on the stack, then dereferences it to read garbage. I\ndeliberately clobber the stack to ensure that it's predictable garbage, so\nwe get:\n\n$ make run_mask_local_escape\n./mask_local_escape\n&g = 0x7fff1b31e6bc\n&g has escaped: 0x7fff1b31e6bc\nvalue is: 0x7f7f7f7f\n\nI think we're using a similar pattern for PG_error_stack, and that's why we\ndon't get any warnings.\n\nIn this case valgrind detects the issue when the bogus data is actually\nread. Run \"valgrind ./mask_local_escape\". But I'm pretty sure I've seen\nother cases where it does not.\n\nSo I'm wondering if the explicit __attribute__((callback(cbfn))) approach\nhas some merits after all, for cassert builds. Assuming we care about this\nerror, since it's a bit of an academic exercise at this point. I just\nneeded to understand what was going on and why there was no warning.\n\n\nDETAILS OF TESTS\n-----\n\nIf I wrap the sigjmp_buf in a struct defined in Pg itself and allow that to\nescape I see the same behaviour, so it's not specific to sigjmp_buf.\n\nI tried adding a dummy guard variable to PG_TRY() and PG_END_TRY() solely\nfor the purpose of tracking this sort of escape. But I notice that a\nwarning from scan-build is only emitted in PG_CATCH() or PG_FINALLY(),\nnever from inside the PG_TRY() body. I'd expect to see a warning from\neither branch, as it's escaping either way.\n\nscan-build will raise other warnings from within the PG_CATCH() block, such\nas if I introduce a\n\n+ int foo = 0;\n+ fprintf(stdout, \"%d\", 10/foo);\n\nso it's not that scan-build as a whole is failing to take the sigsetjmp()\n== 0 branch. It raises *other* warnings. This can also be verified by\nreplacing sigsetjmp() with a dummy static inline function that always takes\none branch or the other.\n\nI landed up writing the experiment code at\nhttps://github.com/ringerc/scrapcode/blob/master/c/clang_return_stack_checks/\nto explore the behaviour some more.\n\nThe file sigjmp_escape.c explores various combinations of guard variables\nand early returns. The file sigjmp_escape_hdr.c and its companions\nsigjmp_escape_hdr_try.{c,h} check whether indirection via separate header\nand compilation unit makes any difference (it didn't).\n\nInitially I found that in my PG_TRY()-alike test code I got a warning like:\n\nsigjmp_escape_hdr.c:36:4: warning: Address of stack memory associated with\nlocal variable '_local_sigjmp_buf' is still referred to by the global\nvariable 'TEST_exception_stack' upon returning to the caller. This will be\na dangling reference\n return;\n ^~~~~~\n\njust like I want to see from inside a PG_TRY() block.\n\nBut with some further testing I noticed that it seems the checker may not\nnotice escapes where there's even the simplest level of indirection, and\nalso that one candidate escape may mask another. I'm not totally sure yet.\n\nIn the sigjmp_escape.c test, if I build it with both inner and outer guards\n(-DUSE_INNER_GUARDS), scan-build will only complain about the inner guard\npointer g_branch_1 escaping. It will not complain about the stack pointer\nto the outer guard escaping, nor about the possibility of\nshould_return_early causing the sigjmp_buf to escape into the global\nsigjmp_buf * jbuf. Yet running\n\n ./sigjmp_escape 1 1\n\nshows that both can occur.\n\nThis still doesn't explain how it *also* misses the escape of &b into jbuf.\nIs it losing track of the unrelated escape when it stops tracking the first\none?\n\nThe test case sigjmp_escape_hdr doesn't attempt to use the guards, and it\nreports the sigjmp_buf escape fine as shown above.\n\nIf sigjmp_escape.c is built with -DUSE_INNER_GUARDS -DPOP_ONLY_INNER_GUARDS\nthen it raises no warnings at all, BUT has both the sigjmp_buf leak AND a\nguard variable stack escape as seen by:\n\n ./sigjmp_escape_inner_pop 1 1\n\nWe've seen above that it loses the outer guard pointer escape because it\ndoesn't track any sort of indirection of assignments.\n\nWhat's a bit surprising is that it *also* fails to complain about the\nescape of the sigjmp_buf pointer &b into the global variable jbuf in this\ncase, even though it successfully detects the escape with other\ncombinations of guard uses. It's like it can't track multiple things at\nonce properly.\n\nRELATED: detecting return from PG_FINALLY()\n--------\n\nNote that even if scan-build did detect the escape of the sigjmp_buf,\nreturning from PG_FINALLY() is a coding error that we cannot detect this\nway since we've restored PG_errror_stack so there's no local auto ptr to\nescape. To do that we'd need our own stack that we pushed in PG_TRY() and\ndidn't pop until PG_END_TRY(), like in the demo patch attached. That works,\nbut adds another local to each PG_TRY() that's otherwise useless. If we\nreally felt like it we could use it to produce a poor-man's backtrace\nthrough each PG_TRY() at the cost of one sizeof(void) per PG_TRY() + some\nconstdata storage, but that seems like a solution looking for a problem.\n\nAlso, AFAICS it's actually harmless, if ugly, to return from PG_CATCH(). It\nshould still be discouraged.\n\n\n-- \n Craig Ringer http://www.2ndQuadrant.com/\n 2ndQuadrant - PostgreSQL Solutions for the Enterprise", "msg_date": "Wed, 9 Sep 2020 14:16:13 +0800", "msg_from": "Craig Ringer <craig@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: [PATCH] Detect escape of ErrorContextCallback stack pointers (and\n from PG_TRY() )" } ]
[ { "msg_contents": "Hi hackers,\n\nRecently I have asked once again by one of our customers about login \ntrigger in postgres. People are migrating to Postgres from Oracle and  \nlooking for Postgres analog of this Oracle feature.\nThis topic is not new:\n\nhttps://www.postgresql.org/message-id/flat/1570308356720-0.post%40n3.nabble.com#4748bcb0c5fc98cec0a735dbdffb0c68\nhttps://www.postgresql.org/message-id/flat/OSAPR01MB507373499CCCEA00EAE79875FE2D0%40OSAPR01MB5073.jpnprd01.prod.outlook.com#ed50c248be32be6955c385ca67d6cdc1\n\nend even session connect/disconnect hooks were sometimes committed (but \nthen reverted).\nAs far as I understand most of the concerns were related with disconnect \nhook.\nPerforming some action on session disconnect is actually much more \ncomplicated than on login.\nBut customers are not needed it, unlike actions performed at session start.\n\nI wonder if we are really going to make some steps in this directions?\nThe discussion above was finished with \"We haven't rejected the concept \naltogether, AFAICT\"\n\nI have tried to resurrect this patch and implement on-connect trigger on \ntop of it.\nThe syntax is almost the same as proposed by Takayuki:\n\nCREATE EVENT TRIGGER mytrigger\nAFTER CONNECTION ON mydatabase\nEXECUTE {PROCEDURE | FUNCTION} myproc();\n\nI have replaced CONNECT with CONNECTION because last keyword is already \nrecognized by Postgres and\nmake ON clause mandatory to avoid shift-reduce conflicts.\n\nActually specifying database name is redundant, because we can define \non-connect trigger only for self database (just because triggers and \nfunctions are local to the database).\nIt may be considered as argument against handling session start using \ntrigger. But it seems to be the most natural mechanism for users.\n\nOn connect trigger can be dropped almost in the same way as normal (on \nrelation) trigger, but with specifying name of the database instead of \nrelation name:\n\nDROP TRIGGER mytrigger ON mydatabase;\n\nIt is possible to define arbitrary number of on-connect triggers with \ndifferent names.\n\nI attached my prototype implementation of this feature.\nI just to be sure first that this feature will be interested to community.\nIf so, I will continue work in it and prepare new version of the patch \nfor the commitfest.\n\nExample\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Thu, 3 Sep 2020 16:42:44 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "On login trigger: take three" }, { "msg_contents": "Hi\n\nčt 3. 9. 2020 v 15:43 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n> Hi hackers,\n>\n> Recently I have asked once again by one of our customers about login\n> trigger in postgres. People are migrating to Postgres from Oracle and\n> looking for Postgres analog of this Oracle feature.\n> This topic is not new:\n>\n>\n> https://www.postgresql.org/message-id/flat/1570308356720-0.post%40n3.nabble.com#4748bcb0c5fc98cec0a735dbdffb0c68\n>\n> https://www.postgresql.org/message-id/flat/OSAPR01MB507373499CCCEA00EAE79875FE2D0%40OSAPR01MB5073.jpnprd01.prod.outlook.com#ed50c248be32be6955c385ca67d6cdc1\n>\n> end even session connect/disconnect hooks were sometimes committed (but\n> then reverted).\n> As far as I understand most of the concerns were related with disconnect\n> hook.\n> Performing some action on session disconnect is actually much more\n> complicated than on login.\n> But customers are not needed it, unlike actions performed at session start.\n>\n> I wonder if we are really going to make some steps in this directions?\n> The discussion above was finished with \"We haven't rejected the concept\n> altogether, AFAICT\"\n>\n> I have tried to resurrect this patch and implement on-connect trigger on\n> top of it.\n> The syntax is almost the same as proposed by Takayuki:\n>\n> CREATE EVENT TRIGGER mytrigger\n> AFTER CONNECTION ON mydatabase\n> EXECUTE {PROCEDURE | FUNCTION} myproc();\n>\n> I have replaced CONNECT with CONNECTION because last keyword is already\n> recognized by Postgres and\n> make ON clause mandatory to avoid shift-reduce conflicts.\n>\n> Actually specifying database name is redundant, because we can define\n> on-connect trigger only for self database (just because triggers and\n> functions are local to the database).\n> It may be considered as argument against handling session start using\n> trigger. But it seems to be the most natural mechanism for users.\n>\n> On connect trigger can be dropped almost in the same way as normal (on\n> relation) trigger, but with specifying name of the database instead of\n> relation name:\n>\n> DROP TRIGGER mytrigger ON mydatabase;\n>\n> It is possible to define arbitrary number of on-connect triggers with\n> different names.\n>\n> I attached my prototype implementation of this feature.\n> I just to be sure first that this feature will be interested to community.\n> If so, I will continue work in it and prepare new version of the patch\n> for the commitfest.\n>\n>\nI have a customer that requires this feature too. Now it uses a solution\nbased on dll session autoloading. Native solution can be great.\n\n+1\n\nPavel\n\nExample\n>\n> --\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>\n\nHičt 3. 9. 2020 v 15:43 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:Hi hackers,\n\nRecently I have asked once again by one of our customers about login \ntrigger in postgres. People are migrating to Postgres from Oracle and  \nlooking for Postgres analog of this Oracle feature.\nThis topic is not new:\n\nhttps://www.postgresql.org/message-id/flat/1570308356720-0.post%40n3.nabble.com#4748bcb0c5fc98cec0a735dbdffb0c68\nhttps://www.postgresql.org/message-id/flat/OSAPR01MB507373499CCCEA00EAE79875FE2D0%40OSAPR01MB5073.jpnprd01.prod.outlook.com#ed50c248be32be6955c385ca67d6cdc1\n\nend even session connect/disconnect hooks were sometimes committed (but \nthen reverted).\nAs far as I understand most of the concerns were related with disconnect \nhook.\nPerforming some action on session disconnect is actually much more \ncomplicated than on login.\nBut customers are not needed it, unlike actions performed at session start.\n\nI wonder if we are really going to make some steps in this directions?\nThe discussion above was finished with \"We haven't rejected the concept \naltogether, AFAICT\"\n\nI have tried to resurrect this patch and implement on-connect trigger on \ntop of it.\nThe syntax is almost the same as proposed by Takayuki:\n\nCREATE EVENT TRIGGER mytrigger\nAFTER CONNECTION ON mydatabase\nEXECUTE {PROCEDURE | FUNCTION} myproc();\n\nI have replaced CONNECT with CONNECTION because last keyword is already \nrecognized by Postgres and\nmake ON clause mandatory to avoid shift-reduce conflicts.\n\nActually specifying database name is redundant, because we can define \non-connect trigger only for self database (just because triggers and \nfunctions are local to the database).\nIt may be considered as argument against handling session start using \ntrigger. But it seems to be the most natural mechanism for users.\n\nOn connect trigger can be dropped almost in the same way as normal (on \nrelation) trigger, but with specifying name of the database instead of \nrelation name:\n\nDROP TRIGGER mytrigger ON mydatabase;\n\nIt is possible to define arbitrary number of on-connect triggers with \ndifferent names.\n\nI attached my prototype implementation of this feature.\nI just to be sure first that this feature will be interested to community.\nIf so, I will continue work in it and prepare new version of the patch \nfor the commitfest.\nI have a customer that requires this feature too. Now it uses a solution based on dll session autoloading.  Native solution can be great.+1Pavel\nExample\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Thu, 3 Sep 2020 16:18:41 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "From: Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\r\n> Recently I have asked once again by one of our customers about login trigger in\r\n> postgres. People are migrating to Postgres from Oracle and looking for Postgres\r\n> analog of this Oracle feature.\r\n> This topic is not new:\r\n\r\n> I attached my prototype implementation of this feature.\r\n> I just to be sure first that this feature will be interested to community.\r\n> If so, I will continue work in it and prepare new version of the patch for the\r\n> commitfest.\r\n\r\nThanks a lot for taking on this! +10\r\n\r\n> It may be considered as argument against handling session start using trigger.\r\n> But it seems to be the most natural mechanism for users.\r\n\r\nYeah, it's natural, just like the Unix shells run some shell scripts in the home directory.\r\n\r\n\r\nRegards\r\nTakayuki Tsunakawa\r\n\r\n", "msg_date": "Fri, 4 Sep 2020 00:11:46 +0000", "msg_from": "\"tsunakawa.takay@fujitsu.com\" <tsunakawa.takay@fujitsu.com>", "msg_from_op": false, "msg_subject": "RE: On login trigger: take three" }, { "msg_contents": "Sorry, attached version of the patch is missing changes in one file. \nHere is it correct patch.\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 4 Sep 2020 18:59:17 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 03.09.2020 17:18, Pavel Stehule wrote:\n> Hi\n>\n> čt 3. 9. 2020 v 15:43 odesílatel Konstantin Knizhnik \n> <k.knizhnik@postgrespro.ru <mailto:k.knizhnik@postgrespro.ru>> napsal:\n>\n> Hi hackers,\n>\n> Recently I have asked once again by one of our customers about login\n> trigger in postgres. People are migrating to Postgres from Oracle and\n> looking for Postgres analog of this Oracle feature.\n> This topic is not new:\n>\n> https://www.postgresql.org/message-id/flat/1570308356720-0.post%40n3.nabble.com#4748bcb0c5fc98cec0a735dbdffb0c68\n> https://www.postgresql.org/message-id/flat/OSAPR01MB507373499CCCEA00EAE79875FE2D0%40OSAPR01MB5073.jpnprd01.prod.outlook.com#ed50c248be32be6955c385ca67d6cdc1\n>\n> end even session connect/disconnect hooks were sometimes committed\n> (but\n> then reverted).\n> As far as I understand most of the concerns were related with\n> disconnect\n> hook.\n> Performing some action on session disconnect is actually much more\n> complicated than on login.\n> But customers are not needed it, unlike actions performed at\n> session start.\n>\n> I wonder if we are really going to make some steps in this directions?\n> The discussion above was finished with \"We haven't rejected the\n> concept\n> altogether, AFAICT\"\n>\n> I have tried to resurrect this patch and implement on-connect\n> trigger on\n> top of it.\n> The syntax is almost the same as proposed by Takayuki:\n>\n> CREATE EVENT TRIGGER mytrigger\n> AFTER CONNECTION ON mydatabase\n> EXECUTE {PROCEDURE | FUNCTION} myproc();\n>\n> I have replaced CONNECT with CONNECTION because last keyword is\n> already\n> recognized by Postgres and\n> make ON clause mandatory to avoid shift-reduce conflicts.\n>\n> Actually specifying database name is redundant, because we can define\n> on-connect trigger only for self database (just because triggers and\n> functions are local to the database).\n> It may be considered as argument against handling session start using\n> trigger. But it seems to be the most natural mechanism for users.\n>\n> On connect trigger can be dropped almost in the same way as normal\n> (on\n> relation) trigger, but with specifying name of the database\n> instead of\n> relation name:\n>\n> DROP TRIGGER mytrigger ON mydatabase;\n>\n> It is possible to define arbitrary number of on-connect triggers with\n> different names.\n>\n> I attached my prototype implementation of this feature.\n> I just to be sure first that this feature will be interested to\n> community.\n> If so, I will continue work in it and prepare new version of the\n> patch\n> for the commitfest.\n>\n>\n> I have a customer that requires this feature too. Now it uses a \n> solution based on dll session autoloading.  Native solution can be great.\n>\n> +1\n\nI realized that on connect trigger should be implemented as EVENT TRIGGER.\nSo I have reimplemented my patch using event trigger and use \nsession_start even name to make it more consistent with other events.\nNow on login triggers can be created in this way:\n\ncreate table connects(id serial, who text);\ncreate function on_login_proc() returns event_trigger as $$\nbegin\n   insert into connects (who) values (current_user());\n   raise notice 'You are welcome!';\nend;\n$$ language plpgsql;\ncreate event trigger on_login_trigger on session_start execute procedure \non_login_proc();\nalter event trigger on_login_trigger enable always;", "msg_date": "Fri, 11 Sep 2020 13:42:17 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi\n\nI am checking last patch, and there are notices\n\n1. disable_session_start_trigger should be SU_BACKEND instead SUSET\n\n2. The documentation should be enhanced - there is not any note about\nbehave when there are unhandled exceptions, about motivation for this event\ntrigger\n\n3. regress tests should be enhanced - the cases with exceptions are not\ntested\n\n4. This trigger is not executed again after RESET ALL or DISCARD ALL - it\ncan be a problem if somebody wants to use this trigger for initialisation\nof some session objects with some pooling solutions.\n\n5. The handling errors don't work well for canceling. If event trigger\nwaits for some event, then cancel disallow connect although connected user\nis superuser\n\nCREATE OR REPLACE FUNCTION on_login_proc2() RETURNS EVENT_TRIGGER AS $$\nbegin perform pg_sleep(10000); raise notice '%', fx1(100);raise notice\n'kuku kuku'; end $$ language plpgsql;\n\nprobably nobody will use pg_sleep in this routine, but there can be wait on\nsome locks ...\n\nRegards\n\nPavel\n\nHiI am checking last patch, and there are notices1. disable_session_start_trigger should be SU_BACKEND instead SUSET2. The documentation should be enhanced - there is not any note about behave when there are unhandled exceptions, about motivation for this event trigger3. regress tests should be enhanced - the cases with exceptions are not tested4. This trigger is not executed again after RESET ALL or DISCARD ALL - it can be a problem if somebody wants to use this trigger for initialisation of some session objects with some pooling solutions.5. The handling errors don't work well for canceling. If event trigger waits for some event, then cancel disallow connect although connected user is superuserCREATE OR REPLACE FUNCTION on_login_proc2() RETURNS EVENT_TRIGGER AS $$ begin perform pg_sleep(10000); raise notice '%', fx1(100);raise notice 'kuku kuku'; end  $$ language plpgsql;probably nobody will use pg_sleep in this routine, but there can be wait on some locks ...RegardsPavel", "msg_date": "Mon, 14 Sep 2020 11:44:54 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 14.09.2020 12:44, Pavel Stehule wrote:\n> Hi\n>\n> I am checking last patch, and there are notices\n>\n> 1. disable_session_start_trigger should be SU_BACKEND instead SUSET\n>\n> 2. The documentation should be enhanced - there is not any note about \n> behave when there are unhandled exceptions, about motivation for this \n> event trigger\n>\n> 3. regress tests should be enhanced - the cases with exceptions are \n> not tested\n>\n> 4. This trigger is not executed again after RESET ALL or DISCARD ALL - \n> it can be a problem if somebody wants to use this trigger for \n> initialisation of some session objects with some pooling solutions.\n>\n> 5. The handling errors don't work well for canceling. If event trigger \n> waits for some event, then cancel disallow connect although connected \n> user is superuser\n>\n> CREATE OR REPLACE FUNCTION on_login_proc2() RETURNS EVENT_TRIGGER AS \n> $$ begin perform pg_sleep(10000); raise notice '%', fx1(100);raise \n> notice 'kuku kuku'; end  $$ language plpgsql;\n>\n> probably nobody will use pg_sleep in this routine, but there can be \n> wait on some locks ...\n>\n> Regards\n>\n> Pavel\n>\n>\n>\n\nHi\nThank you very much for looking at my patch for connection triggers.\nI have fixed 1-3 issues in the attached patch.\nConcerning 4 and 5 I have some doubts:\n\n4. Should I add some extra GUC to allow firing of session_start trigger \nin case of  RESET ALL or DISCARD ALL ?\nLooks like such behavior contradicts with event name \"session_start\"...\nAnd do we really need it? If some pooler is using RESET ALL/DISCARD ALL \nto emulate session semantic then  most likely it provides way to define \ncustom actions which\nshould be perform for session initialization. As far as I know, for \nexample pgbouncer allows do define own on-connect hooks.\n\n5. I do not quite understand your concern. If I define  trigger \nprocedure which is  blocked (for example as in your example), then I can \nuse pg_cancel_backend to interrupt execution of login trigger and \nsuperuser can login. What should be changed here?\n\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Mon, 14 Sep 2020 17:12:42 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "po 14. 9. 2020 v 16:12 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 14.09.2020 12:44, Pavel Stehule wrote:\n> > Hi\n> >\n> > I am checking last patch, and there are notices\n> >\n> > 1. disable_session_start_trigger should be SU_BACKEND instead SUSET\n> >\n> > 2. The documentation should be enhanced - there is not any note about\n> > behave when there are unhandled exceptions, about motivation for this\n> > event trigger\n> >\n> > 3. regress tests should be enhanced - the cases with exceptions are\n> > not tested\n> >\n> > 4. This trigger is not executed again after RESET ALL or DISCARD ALL -\n> > it can be a problem if somebody wants to use this trigger for\n> > initialisation of some session objects with some pooling solutions.\n> >\n> > 5. The handling errors don't work well for canceling. If event trigger\n> > waits for some event, then cancel disallow connect although connected\n> > user is superuser\n> >\n> > CREATE OR REPLACE FUNCTION on_login_proc2() RETURNS EVENT_TRIGGER AS\n> > $$ begin perform pg_sleep(10000); raise notice '%', fx1(100);raise\n> > notice 'kuku kuku'; end $$ language plpgsql;\n> >\n> > probably nobody will use pg_sleep in this routine, but there can be\n> > wait on some locks ...\n> >\n> > Regards\n> >\n> > Pavel\n> >\n> >\n> >\n>\n> Hi\n> Thank you very much for looking at my patch for connection triggers.\n> I have fixed 1-3 issues in the attached patch.\n> Concerning 4 and 5 I have some doubts:\n>\n> 4. Should I add some extra GUC to allow firing of session_start trigger\n> in case of RESET ALL or DISCARD ALL ?\n> Looks like such behavior contradicts with event name \"session_start\"...\n> And do we really need it? If some pooler is using RESET ALL/DISCARD ALL\n> to emulate session semantic then most likely it provides way to define\n> custom actions which\n> should be perform for session initialization. As far as I know, for\n> example pgbouncer allows do define own on-connect hooks.\n>\n\nIf we introduce buildin session trigger , we should to define what is the\nsession. Your design is much more related to the process than to session.\nSo the correct name should be \"process_start\" trigger, or some should be\ndifferent. I think there are two different events - process_start, and\nsession_start, and there should be two different event triggers. Maybe the\nname \"session_start\" is just ambiguous and should be used with a different\nname.\n\n\n>\n> 5. I do not quite understand your concern. If I define trigger\n> procedure which is blocked (for example as in your example), then I can\n> use pg_cancel_backend to interrupt execution of login trigger and\n> superuser can login. What should be changed here?\n>\n\nYou cannot run pg_cancel_backend, because you cannot open a new session.\nThere is a cycle.\n\nRegards\n\nPavel\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\npo 14. 9. 2020 v 16:12 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\nOn 14.09.2020 12:44, Pavel Stehule wrote:\n> Hi\n>\n> I am checking last patch, and there are notices\n>\n> 1. disable_session_start_trigger should be SU_BACKEND instead SUSET\n>\n> 2. The documentation should be enhanced - there is not any note about \n> behave when there are unhandled exceptions, about motivation for this \n> event trigger\n>\n> 3. regress tests should be enhanced - the cases with exceptions are \n> not tested\n>\n> 4. This trigger is not executed again after RESET ALL or DISCARD ALL - \n> it can be a problem if somebody wants to use this trigger for \n> initialisation of some session objects with some pooling solutions.\n>\n> 5. The handling errors don't work well for canceling. If event trigger \n> waits for some event, then cancel disallow connect although connected \n> user is superuser\n>\n> CREATE OR REPLACE FUNCTION on_login_proc2() RETURNS EVENT_TRIGGER AS \n> $$ begin perform pg_sleep(10000); raise notice '%', fx1(100);raise \n> notice 'kuku kuku'; end  $$ language plpgsql;\n>\n> probably nobody will use pg_sleep in this routine, but there can be \n> wait on some locks ...\n>\n> Regards\n>\n> Pavel\n>\n>\n>\n\nHi\nThank you very much for looking at my patch for connection triggers.\nI have fixed 1-3 issues in the attached patch.\nConcerning 4 and 5 I have some doubts:\n\n4. Should I add some extra GUC to allow firing of session_start trigger \nin case of  RESET ALL or DISCARD ALL ?\nLooks like such behavior contradicts with event name \"session_start\"...\nAnd do we really need it? If some pooler is using RESET ALL/DISCARD ALL \nto emulate session semantic then  most likely it provides way to define \ncustom actions which\nshould be perform for session initialization. As far as I know, for \nexample pgbouncer allows do define own on-connect hooks.If we introduce buildin session trigger , we should to define what is the session. Your design is much more related to the process than to session. So the correct name should be \"process_start\" trigger, or some should be different. I think there are two different events - process_start, and session_start, and there should be two different event triggers. Maybe the name \"session_start\" is just ambiguous and should be used with a different name.   \n\n5. I do not quite understand your concern. If I define  trigger \nprocedure which is  blocked (for example as in your example), then I can \nuse pg_cancel_backend to interrupt execution of login trigger and \nsuperuser can login. What should be changed here?You cannot run pg_cancel_backend, because you cannot open a new session. There is a cycle.RegardsPavel \n\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Mon, 14 Sep 2020 16:34:22 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 14.09.2020 17:34, Pavel Stehule wrote:\n> If we introduce buildin session trigger , we should to define what is \n> the session. Your design is much more related to the process than to \n> session. So the correct name should be \"process_start\" trigger, or \n> some should be different. I think there are two different events - \n> process_start, and session_start, and there should be two different \n> event triggers. Maybe the name \"session_start\" is just ambiguous and \n> should be used with a different name.\n\nI agree.\nI can rename trigger to backend_start or process_start or whatever else.\n\n>\n> 5. I do not quite understand your concern. If I define trigger\n> procedure which is  blocked (for example as in your example), then\n> I can\n> use pg_cancel_backend to interrupt execution of login trigger and\n> superuser can login. What should be changed here?\n>\n>\n> You cannot run pg_cancel_backend, because you cannot open a new \n> session. There is a cycle.\n\nIt is always possible to login by disabling startup triggers using \ndisable_session_start_trigger GUC:\n\npsql \"dbname=postgres options='-c disable_session_start_trigger=true'\"\n\n\n\n\n\n\n\n\n\n\nOn 14.09.2020 17:34, Pavel Stehule\n wrote:\n\n\n\nIf we introduce buildin session trigger , we should\n to define what is the session. Your design is much more related\n to the process than to session. So the correct name should be\n \"process_start\" trigger, or some should be different. I think\n there are two different events - process_start, and\n session_start, and there should be two different event triggers.\n Maybe the name \"session_start\" is just ambiguous and should be\n used with a different name.  \n\n\n\n I agree.\n I can rename trigger to backend_start or process_start or whatever\n else.\n\n\n\n\n \n\n\n 5. I do not quite understand your concern. If I define \n trigger \n procedure which is  blocked (for example as in your\n example), then I can \n use pg_cancel_backend to interrupt execution of login\n trigger and \n superuser can login. What should be changed here?\n\n\n\nYou cannot run pg_cancel_backend, because you cannot open\n a new session. There is a cycle.\n\n\n\n\n It is always possible to login by disabling startup triggers using\n disable_session_start_trigger GUC:\n\n psql \"dbname=postgres options='-c\n disable_session_start_trigger=true'\"", "msg_date": "Mon, 14 Sep 2020 18:53:10 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "po 14. 9. 2020 v 17:53 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 14.09.2020 17:34, Pavel Stehule wrote:\n>\n> If we introduce buildin session trigger , we should to define what is the\n> session. Your design is much more related to the process than to session.\n> So the correct name should be \"process_start\" trigger, or some should be\n> different. I think there are two different events - process_start, and\n> session_start, and there should be two different event triggers. Maybe the\n> name \"session_start\" is just ambiguous and should be used with a different\n> name.\n>\n>\n> I agree.\n> I can rename trigger to backend_start or process_start or whatever else.\n>\n\nCreating a good name can be hard - it is not called for any process - so\nmaybe \"user_backend_start\" ?\n\n\n>\n>\n>>\n>> 5. I do not quite understand your concern. If I define trigger\n>> procedure which is blocked (for example as in your example), then I can\n>> use pg_cancel_backend to interrupt execution of login trigger and\n>> superuser can login. What should be changed here?\n>>\n>\n> You cannot run pg_cancel_backend, because you cannot open a new session.\n> There is a cycle.\n>\n>\n> It is always possible to login by disabling startup triggers using\n> disable_session_start_trigger GUC:\n>\n> psql \"dbname=postgres options='-c disable_session_start_trigger=true'\"\n>\n\nsure, I know. Just this behavior can be a very unpleasant surprise, and my\nquestion is if it can be fixed. Creating custom libpq variables can be the\nstop for people that use pgAdmin.\n\npo 14. 9. 2020 v 17:53 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n\n\nOn 14.09.2020 17:34, Pavel Stehule\n wrote:\n\n\nIf we introduce buildin session trigger , we should\n to define what is the session. Your design is much more related\n to the process than to session. So the correct name should be\n \"process_start\" trigger, or some should be different. I think\n there are two different events - process_start, and\n session_start, and there should be two different event triggers.\n Maybe the name \"session_start\" is just ambiguous and should be\n used with a different name.  \n\n\n\n I agree.\n I can rename trigger to backend_start or process_start or whatever\n else.Creating a good name can be hard - it is not called for any process - so maybe \"user_backend_start\" ?  \n\n\n\n\n \n\n\n 5. I do not quite understand your concern. If I define \n trigger \n procedure which is  blocked (for example as in your\n example), then I can \n use pg_cancel_backend to interrupt execution of login\n trigger and \n superuser can login. What should be changed here?\n\n\n\nYou cannot run pg_cancel_backend, because you cannot open\n a new session. There is a cycle.\n\n\n\n\n It is always possible to login by disabling startup triggers using\n disable_session_start_trigger GUC:\n\n psql \"dbname=postgres options='-c\n disable_session_start_trigger=true'\"sure, I know. Just this behavior can be a very unpleasant surprise, and my question is if it can be fixed.  Creating custom libpq variables can be the stop for people that use pgAdmin.", "msg_date": "Mon, 14 Sep 2020 18:11:46 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Tue, Sep 15, 2020 at 2:12 AM Pavel Stehule <pavel.stehule@gmail.com> wrote:\n>\n>>\n>> It is always possible to login by disabling startup triggers using disable_session_start_trigger GUC:\n>>\n>> psql \"dbname=postgres options='-c disable_session_start_trigger=true'\"\n>\n>\n> sure, I know. Just this behavior can be a very unpleasant surprise, and my question is if it can be fixed. Creating custom libpq variables can be the stop for people that use pgAdmin.\n>\n\nHi,\n\nI thought in the case of using pgAdmin (assuming you can connect as\nsuperuser to a database, say the default \"postgres\" maintenance\ndatabase, that doesn't have an EVENT TRIGGER defined for the\nsession_start event) you could issue the query \"ALTER SYSTEM SET\ndisable_session_start_trigger TO true;\" and then reload the\nconfiguration?\n\nAnyway, I am wondering if this patch is still being actively developed/improved?\n\nRegarding the last-posted patch, I'd like to give some feedback. I\nfound that the documentation part wouldn't build because of errors in\nthe SGML tags. There are some grammatical errors too, and some minor\ninconsistencies with the current documentation, and some descriptions\ncould be improved. I think that a colon separator should be added to\nthe NOTICE message for superuser, so it's clear exactly where the text\nof the underlying error message starts. Also, I think that\n\"client_connection\" is perhaps a better and more intuitive event name\nthan \"session_start\", or the suggested \"user_backend_start\".\nI've therefore attached an updated patch with these suggested minor\nimprovements, please take a look and see what you think (please\ncompare with the original patch).\n\nRegards,\nGreg Nancarrow\nFujitsu Australia", "msg_date": "Fri, 4 Dec 2020 11:50:10 +1100", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "\n\nOn 04.12.2020 3:50, Greg Nancarrow wrote:\n> On Tue, Sep 15, 2020 at 2:12 AM Pavel Stehule <pavel.stehule@gmail.com> wrote:\n>>> It is always possible to login by disabling startup triggers using disable_session_start_trigger GUC:\n>>>\n>>> psql \"dbname=postgres options='-c disable_session_start_trigger=true'\"\n>>\n>> sure, I know. Just this behavior can be a very unpleasant surprise, and my question is if it can be fixed. Creating custom libpq variables can be the stop for people that use pgAdmin.\n>>\n> Hi,\n>\n> I thought in the case of using pgAdmin (assuming you can connect as\n> superuser to a database, say the default \"postgres\" maintenance\n> database, that doesn't have an EVENT TRIGGER defined for the\n> session_start event) you could issue the query \"ALTER SYSTEM SET\n> disable_session_start_trigger TO true;\" and then reload the\n> configuration?\nAs far as I understand Pavel concern was about the case when superuser \ndefines wrong login trigger which prevents login to the system\nall user including himself. Right now solution of this problem is to \ninclude \"options='-c disable_session_start_trigger=true'\" in connection \nstring.\nI do not know if it can be done with pgAdmin.\n>\n> Anyway, I am wondering if this patch is still being actively developed/improved?\n\nI do not know what else has to be improved.\nIf you, Pavel or anybody else have some suggestions: please let me know.\n>\n> Regarding the last-posted patch, I'd like to give some feedback. I\n> found that the documentation part wouldn't build because of errors in\n> the SGML tags. There are some grammatical errors too, and some minor\n> inconsistencies with the current documentation, and some descriptions\n> could be improved. I think that a colon separator should be added to\n> the NOTICE message for superuser, so it's clear exactly where the text\n> of the underlying error message starts. Also, I think that\n> \"client_connection\" is perhaps a better and more intuitive event name\n> than \"session_start\", or the suggested \"user_backend_start\".\n> I've therefore attached an updated patch with these suggested minor\n> improvements, please take a look and see what you think (please\n> compare with the original patch).\n\nThank you very much for detecting the problems and much more thanks for \nfixing them and providing your version of the patch.\nI have nothing against renaming \"session_start\" to \"client_connection\".\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Fri, 4 Dec 2020 13:05:45 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Fri, Dec 4, 2020 at 9:05 PM Konstantin Knizhnik\n<k.knizhnik@postgrespro.ru> wrote:\n>\n> As far as I understand Pavel concern was about the case when superuser\n> defines wrong login trigger which prevents login to the system\n> all user including himself. Right now solution of this problem is to\n> include \"options='-c disable_session_start_trigger=true'\" in connection\n> string.\n> I do not know if it can be done with pgAdmin.\n> >\n\nAs an event trigger is tied to a particular database, and a GUC is\nglobal to the cluster, as long as there is one database in the cluster\nfor which an event trigger for the \"client_connection\" event is NOT\ndefined (say the default \"postgres\" maintenance database), then the\nsuperuser can always connect to that database, issue \"ALTER SYSTEM SET\ndisable_client_connection_trigger TO true\" and reload the\nconfiguration. I tested this with pgAdmin4 and it worked fine for me,\nto allow login to a database for which login was previously prevented\ndue to a badly-defined logon trigger.\n\nPavel, is this an acceptable solution or do you still see problems\nwith this approach?\n\n\nRegards,\nGreg Nancarrow\nFujitsu Australia\n\n\n", "msg_date": "Tue, 8 Dec 2020 11:17:33 +1100", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "út 8. 12. 2020 v 1:17 odesílatel Greg Nancarrow <gregn4422@gmail.com>\nnapsal:\n\n> On Fri, Dec 4, 2020 at 9:05 PM Konstantin Knizhnik\n> <k.knizhnik@postgrespro.ru> wrote:\n> >\n> > As far as I understand Pavel concern was about the case when superuser\n> > defines wrong login trigger which prevents login to the system\n> > all user including himself. Right now solution of this problem is to\n> > include \"options='-c disable_session_start_trigger=true'\" in connection\n> > string.\n> > I do not know if it can be done with pgAdmin.\n> > >\n>\n> As an event trigger is tied to a particular database, and a GUC is\n> global to the cluster, as long as there is one database in the cluster\n> for which an event trigger for the \"client_connection\" event is NOT\n> defined (say the default \"postgres\" maintenance database), then the\n> superuser can always connect to that database, issue \"ALTER SYSTEM SET\n> disable_client_connection_trigger TO true\" and reload the\n> configuration. I tested this with pgAdmin4 and it worked fine for me,\n> to allow login to a database for which login was previously prevented\n> due to a badly-defined logon trigger.\n>\n\nyes, it can work .. Maybe for this operation only database owner rights\nshould be necessary. The super user is maybe too strong.\n\nThere are two maybe generic questions?\n\n1. Maybe we can introduce more generic GUC for all event triggers like\ndisable_event_triggers? This GUC can be checked only by the database owner\nor super user. It can be an alternative ALTER TABLE DISABLE TRIGGER ALL. It\ncan be protection against necessity to restart to single mode to repair the\nevent trigger. I think so more generic solution is better than special\ndisable_client_connection_trigger GUC.\n\n2. I have no objection against client_connection. It is probably better for\nthe mentioned purpose - possibility to block connection to database. Can be\ninteresting, and I am not sure how much work it is to introduce the second\nevent - session_start. This event should be started after connecting - so\nthe exception there doesn't block connect, and should be started also after\nthe new statement \"DISCARD SESSION\", that will be started automatically\nafter DISCARD ALL. This feature should not be implemented in first step,\nbut it can be a plan for support pooled connections\n\nRegards\n\nPavel\n\n\n\n\n> Pavel, is this an acceptable solution or do you still see problems\n> with this approach?\n>\n>\n> Regards,\n> Greg Nancarrow\n> Fujitsu Australia\n>\n\nút 8. 12. 2020 v 1:17 odesílatel Greg Nancarrow <gregn4422@gmail.com> napsal:On Fri, Dec 4, 2020 at 9:05 PM Konstantin Knizhnik\n<k.knizhnik@postgrespro.ru> wrote:\n>\n> As far as I understand Pavel concern was about the case when superuser\n> defines wrong login trigger which prevents login to the system\n> all user including himself. Right now solution of this problem is to\n> include \"options='-c disable_session_start_trigger=true'\" in connection\n> string.\n> I do not know if it can be done with pgAdmin.\n> >\n\nAs an event trigger is tied to a particular database, and a GUC is\nglobal to the cluster, as long as there is one database in the cluster\nfor which an event trigger for the \"client_connection\" event is NOT\ndefined (say the default \"postgres\" maintenance database), then the\nsuperuser can always connect to that database, issue \"ALTER SYSTEM SET\ndisable_client_connection_trigger TO true\" and reload the\nconfiguration. I tested this with pgAdmin4 and it worked fine for me,\nto allow login to a database for which login was previously prevented\ndue to a badly-defined logon trigger.yes, it can work .. Maybe for this operation only database owner rights should be necessary. The super user is maybe too strong.There are two maybe generic questions?1. Maybe we can introduce more generic GUC for all event triggers like disable_event_triggers? This GUC can be checked only by the database owner or super user. It can be an alternative ALTER TABLE DISABLE TRIGGER ALL. It can be protection against necessity to restart to single mode to repair the event trigger. I think so more generic solution is better than special disable_client_connection_trigger GUC.2. I have no objection against client_connection. It is probably better for the mentioned purpose - possibility to block connection to database. Can be interesting, and I am not sure how much work it is to introduce the second event - session_start. This event should be started after connecting - so the exception there doesn't block connect, and should be started also after the new statement \"DISCARD SESSION\", that will be started automatically after DISCARD ALL.  This feature should not be implemented in first step, but it can be a plan for support pooled connections RegardsPavel \n\nPavel, is this an acceptable solution or do you still see problems\nwith this approach?\n\n\nRegards,\nGreg Nancarrow\nFujitsu Australia", "msg_date": "Tue, 8 Dec 2020 05:26:08 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Tue, Dec 8, 2020 at 3:26 PM Pavel Stehule <pavel.stehule@gmail.com> wrote:\n>\n>\n> There are two maybe generic questions?\n>\n> 1. Maybe we can introduce more generic GUC for all event triggers like disable_event_triggers? This GUC can be checked only by the database owner or super user. It can be an alternative ALTER TABLE DISABLE TRIGGER ALL. It can be protection against necessity to restart to single mode to repair the event trigger. I think so more generic solution is better than special disable_client_connection_trigger GUC.\n>\n> 2. I have no objection against client_connection. It is probably better for the mentioned purpose - possibility to block connection to database. Can be interesting, and I am not sure how much work it is to introduce the second event - session_start. This event should be started after connecting - so the exception there doesn't block connect, and should be started also after the new statement \"DISCARD SESSION\", that will be started automatically after DISCARD ALL. This feature should not be implemented in first step, but it can be a plan for support pooled connections\n>\n\nI've created a separate patch to address question (1), rather than\ninclude it in the main patch, which I've adjusted accordingly. I'll\nleave question (2) until another time, as you suggest.\nSee the attached patches.\n\nRegards,\nGreg Nancarrow\nFujitsu Australia", "msg_date": "Wed, 9 Dec 2020 23:17:14 +1100", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "st 9. 12. 2020 v 13:17 odesílatel Greg Nancarrow <gregn4422@gmail.com>\nnapsal:\n\n> On Tue, Dec 8, 2020 at 3:26 PM Pavel Stehule <pavel.stehule@gmail.com>\n> wrote:\n> >\n> >\n> > There are two maybe generic questions?\n> >\n> > 1. Maybe we can introduce more generic GUC for all event triggers like\n> disable_event_triggers? This GUC can be checked only by the database owner\n> or super user. It can be an alternative ALTER TABLE DISABLE TRIGGER ALL. It\n> can be protection against necessity to restart to single mode to repair the\n> event trigger. I think so more generic solution is better than special\n> disable_client_connection_trigger GUC.\n> >\n> > 2. I have no objection against client_connection. It is probably better\n> for the mentioned purpose - possibility to block connection to database.\n> Can be interesting, and I am not sure how much work it is to introduce the\n> second event - session_start. This event should be started after connecting\n> - so the exception there doesn't block connect, and should be started also\n> after the new statement \"DISCARD SESSION\", that will be started\n> automatically after DISCARD ALL. This feature should not be implemented in\n> first step, but it can be a plan for support pooled connections\n> >\n>\n\nPGC_SU_BACKEND is too strong, there should be PGC_BACKEND if this option\ncan be used by database owner\n\nPavel\n\n\n> I've created a separate patch to address question (1), rather than\n> include it in the main patch, which I've adjusted accordingly. I'll\n> leave question (2) until another time, as you suggest.\n> See the attached patches.\n>\n> Regards,\n> Greg Nancarrow\n> Fujitsu Australia\n>\n\nst 9. 12. 2020 v 13:17 odesílatel Greg Nancarrow <gregn4422@gmail.com> napsal:On Tue, Dec 8, 2020 at 3:26 PM Pavel Stehule <pavel.stehule@gmail.com> wrote:\n>\n>\n> There are two maybe generic questions?\n>\n> 1. Maybe we can introduce more generic GUC for all event triggers like disable_event_triggers? This GUC can be checked only by the database owner or super user. It can be an alternative ALTER TABLE DISABLE TRIGGER ALL. It can be protection against necessity to restart to single mode to repair the event trigger. I think so more generic solution is better than special disable_client_connection_trigger GUC.\n>\n> 2. I have no objection against client_connection. It is probably better for the mentioned purpose - possibility to block connection to database. Can be interesting, and I am not sure how much work it is to introduce the second event - session_start. This event should be started after connecting - so the exception there doesn't block connect, and should be started also after the new statement \"DISCARD SESSION\", that will be started automatically after DISCARD ALL.  This feature should not be implemented in first step, but it can be a plan for support pooled connections\n>PGC_SU_BACKEND is too strong, there should be PGC_BACKEND if this option can be used by database ownerPavel\n\nI've created a separate patch to address question (1), rather than\ninclude it in the main patch, which I've adjusted accordingly. I'll\nleave question (2) until another time, as you suggest.\nSee the attached patches.\n\nRegards,\nGreg Nancarrow\nFujitsu Australia", "msg_date": "Wed, 9 Dec 2020 13:24:48 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi\n\nst 9. 12. 2020 v 13:17 odesílatel Greg Nancarrow <gregn4422@gmail.com>\nnapsal:\n\n> On Tue, Dec 8, 2020 at 3:26 PM Pavel Stehule <pavel.stehule@gmail.com>\n> wrote:\n> >\n> >\n> > There are two maybe generic questions?\n> >\n> > 1. Maybe we can introduce more generic GUC for all event triggers like\n> disable_event_triggers? This GUC can be checked only by the database owner\n> or super user. It can be an alternative ALTER TABLE DISABLE TRIGGER ALL. It\n> can be protection against necessity to restart to single mode to repair the\n> event trigger. I think so more generic solution is better than special\n> disable_client_connection_trigger GUC.\n> >\n> > 2. I have no objection against client_connection. It is probably better\n> for the mentioned purpose - possibility to block connection to database.\n> Can be interesting, and I am not sure how much work it is to introduce the\n> second event - session_start. This event should be started after connecting\n> - so the exception there doesn't block connect, and should be started also\n> after the new statement \"DISCARD SESSION\", that will be started\n> automatically after DISCARD ALL. This feature should not be implemented in\n> first step, but it can be a plan for support pooled connections\n> >\n>\n> I've created a separate patch to address question (1), rather than\n> include it in the main patch, which I've adjusted accordingly. I'll\n> leave question (2) until another time, as you suggest.\n> See the attached patches.\n>\n\nI see two possible questions?\n\n1. when you introduce this event, then the new hook is useless ?\n\n2. what is a performance impact for users that want not to use this\nfeature. What is a overhead of EventTriggerOnConnect and is possible to\nskip this step if database has not any event trigger\n\nPavel\n\n\n> Regards,\n> Greg Nancarrow\n> Fujitsu Australia\n>\n\nHist 9. 12. 2020 v 13:17 odesílatel Greg Nancarrow <gregn4422@gmail.com> napsal:On Tue, Dec 8, 2020 at 3:26 PM Pavel Stehule <pavel.stehule@gmail.com> wrote:\n>\n>\n> There are two maybe generic questions?\n>\n> 1. Maybe we can introduce more generic GUC for all event triggers like disable_event_triggers? This GUC can be checked only by the database owner or super user. It can be an alternative ALTER TABLE DISABLE TRIGGER ALL. It can be protection against necessity to restart to single mode to repair the event trigger. I think so more generic solution is better than special disable_client_connection_trigger GUC.\n>\n> 2. I have no objection against client_connection. It is probably better for the mentioned purpose - possibility to block connection to database. Can be interesting, and I am not sure how much work it is to introduce the second event - session_start. This event should be started after connecting - so the exception there doesn't block connect, and should be started also after the new statement \"DISCARD SESSION\", that will be started automatically after DISCARD ALL.  This feature should not be implemented in first step, but it can be a plan for support pooled connections\n>\n\nI've created a separate patch to address question (1), rather than\ninclude it in the main patch, which I've adjusted accordingly. I'll\nleave question (2) until another time, as you suggest.\nSee the attached patches.I see two possible questions? 1. when you introduce this event, then the new hook is useless ?2. what is a performance impact for users that want not to use this feature. What is a overhead of EventTriggerOnConnect and is possible to skip this step if database has not any event triggerPavel\n\nRegards,\nGreg Nancarrow\nFujitsu Australia", "msg_date": "Wed, 9 Dec 2020 13:34:26 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 09.12.2020 15:34, Pavel Stehule wrote:\n> Hi\n>\n> st 9. 12. 2020 v 13:17 odesílatel Greg Nancarrow <gregn4422@gmail.com \n> <mailto:gregn4422@gmail.com>> napsal:\n>\n> On Tue, Dec 8, 2020 at 3:26 PM Pavel Stehule\n> <pavel.stehule@gmail.com <mailto:pavel.stehule@gmail.com>> wrote:\n> >\n> >\n> > There are two maybe generic questions?\n> >\n> > 1. Maybe we can introduce more generic GUC for all event\n> triggers like disable_event_triggers? This GUC can be checked only\n> by the database owner or super user. It can be an alternative\n> ALTER TABLE DISABLE TRIGGER ALL. It can be protection against\n> necessity to restart to single mode to repair the event trigger. I\n> think so more generic solution is better than special\n> disable_client_connection_trigger GUC.\n> >\n> > 2. I have no objection against client_connection. It is probably\n> better for the mentioned purpose - possibility to block connection\n> to database. Can be interesting, and I am not sure how much work\n> it is to introduce the second event - session_start. This event\n> should be started after connecting - so the exception there\n> doesn't block connect, and should be started also after the new\n> statement \"DISCARD SESSION\", that will be started automatically\n> after DISCARD ALL.  This feature should not be implemented in\n> first step, but it can be a plan for support pooled connections\n> >\n>\n> I've created a separate patch to address question (1), rather than\n> include it in the main patch, which I've adjusted accordingly. I'll\n> leave question (2) until another time, as you suggest.\n> See the attached patches.\n>\n>\n> I see two possible questions?\n>\n> 1. when you introduce this event, then the new hook is useless ?\n>\n> 2. what is a performance impact for users that want not to use this \n> feature. What is a overhead of EventTriggerOnConnect and is possible \n> to skip this step if database has not any event trigger\n\nAs far as I understand this are questions to me rather than to Greg.\n1. Do you mean client_connection_hook? It is used to implement this new \nevent type. It can be also used for other purposes.\n2. Connection overhead is quite large. Supporting on connect hook \nrequires traversal of event trigger relation. But this overhead is \nnegligible comparing with overhead of establishing connection. In any \ncase I did the following test (with local connection):\n\npgbench -C -S -T 100 -P 1 -M prepared postgres\n\nwithout this patch:\ntps = 424.287889 (including connections establishing)\ntps = 952.911068 (excluding connections establishing)\n\nwith this patch (but without any connection trigger defined):\ntps = 434.642947 (including connections establishing)\ntps = 995.525383 (excluding connections establishing)\n\nAs you can see - there is almost now different (patched version is even \nfaster, but it seems to be just \"white noise\".\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n\n\n\n\n\n\nOn 09.12.2020 15:34, Pavel Stehule\n wrote:\n\n\n\n\nHi\n\n\n\nst 9. 12. 2020 v 13:17\n odesílatel Greg Nancarrow <gregn4422@gmail.com>\n napsal:\n\nOn Tue, Dec 8, 2020 at\n 3:26 PM Pavel Stehule <pavel.stehule@gmail.com>\n wrote:\n >\n >\n > There are two maybe generic questions?\n >\n > 1. Maybe we can introduce more generic GUC for all\n event triggers like disable_event_triggers? This GUC can be\n checked only by the database owner or super user. It can be\n an alternative ALTER TABLE DISABLE TRIGGER ALL. It can be\n protection against necessity to restart to single mode to\n repair the event trigger. I think so more generic solution\n is better than special disable_client_connection_trigger\n GUC.\n >\n > 2. I have no objection against client_connection. It is\n probably better for the mentioned purpose - possibility to\n block connection to database. Can be interesting, and I am\n not sure how much work it is to introduce the second event -\n session_start. This event should be started after connecting\n - so the exception there doesn't block connect, and should\n be started also after the new statement \"DISCARD SESSION\",\n that will be started automatically after DISCARD ALL.  This\n feature should not be implemented in first step, but it can\n be a plan for support pooled connections\n >\n\n I've created a separate patch to address question (1),\n rather than\n include it in the main patch, which I've adjusted\n accordingly. I'll\n leave question (2) until another time, as you suggest.\n See the attached patches.\n\n\n\nI see two possible questions?\n\n\n 1. when you introduce this event, then the new hook is\n useless ?\n\n\n2. what is a performance impact for users that want not\n to use this feature. What is a overhead of\n EventTriggerOnConnect and is possible to skip this step if\n database has not any event trigger\n\n\n\n\n As far as I understand this are questions to me rather than to Greg.\n 1. Do you mean client_connection_hook? It is used to implement this\n new event type. It can be also used for other purposes.\n 2. Connection overhead is quite large. Supporting on connect hook\n requires traversal of event trigger relation. But this overhead is\n negligible comparing with overhead of establishing connection. In\n any case I did the following test (with local connection):\n\n pgbench -C -S -T 100 -P 1 -M prepared postgres\n\n without this patch: \n tps = 424.287889 (including connections establishing)\n tps = 952.911068 (excluding connections establishing)\n\n with this patch (but without any connection trigger defined):\n tps = 434.642947 (including connections establishing)\n tps = 995.525383 (excluding connections establishing)\n\n As you can see - there is almost now different (patched version is\n even faster, but it seems to be just \"white noise\".\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Wed, 9 Dec 2020 16:28:12 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "st 9. 12. 2020 v 14:28 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 09.12.2020 15:34, Pavel Stehule wrote:\n>\n> Hi\n>\n> st 9. 12. 2020 v 13:17 odesílatel Greg Nancarrow <gregn4422@gmail.com>\n> napsal:\n>\n>> On Tue, Dec 8, 2020 at 3:26 PM Pavel Stehule <pavel.stehule@gmail.com>\n>> wrote:\n>> >\n>> >\n>> > There are two maybe generic questions?\n>> >\n>> > 1. Maybe we can introduce more generic GUC for all event triggers like\n>> disable_event_triggers? This GUC can be checked only by the database owner\n>> or super user. It can be an alternative ALTER TABLE DISABLE TRIGGER ALL. It\n>> can be protection against necessity to restart to single mode to repair the\n>> event trigger. I think so more generic solution is better than special\n>> disable_client_connection_trigger GUC.\n>> >\n>> > 2. I have no objection against client_connection. It is probably better\n>> for the mentioned purpose - possibility to block connection to database.\n>> Can be interesting, and I am not sure how much work it is to introduce the\n>> second event - session_start. This event should be started after connecting\n>> - so the exception there doesn't block connect, and should be started also\n>> after the new statement \"DISCARD SESSION\", that will be started\n>> automatically after DISCARD ALL. This feature should not be implemented in\n>> first step, but it can be a plan for support pooled connections\n>> >\n>>\n>> I've created a separate patch to address question (1), rather than\n>> include it in the main patch, which I've adjusted accordingly. I'll\n>> leave question (2) until another time, as you suggest.\n>> See the attached patches.\n>>\n>\n> I see two possible questions?\n>\n> 1. when you introduce this event, then the new hook is useless ?\n>\n> 2. what is a performance impact for users that want not to use this\n> feature. What is a overhead of EventTriggerOnConnect and is possible to\n> skip this step if database has not any event trigger\n>\n>\n> As far as I understand this are questions to me rather than to Greg.\n> 1. Do you mean client_connection_hook? It is used to implement this new\n> event type. It can be also used for other purposes.\n>\n\nok. I don't like it, but there are redundant hooks (against event triggers)\nalready.\n\n\n2. Connection overhead is quite large. Supporting on connect hook requires\n> traversal of event trigger relation. But this overhead is negligible\n> comparing with overhead of establishing connection. In any case I did the\n> following test (with local connection):\n>\n> pgbench -C -S -T 100 -P 1 -M prepared postgres\n>\n> without this patch:\n> tps = 424.287889 (including connections establishing)\n> tps = 952.911068 (excluding connections establishing)\n>\n> with this patch (but without any connection trigger defined):\n> tps = 434.642947 (including connections establishing)\n> tps = 995.525383 (excluding connections establishing)\n>\n> As you can see - there is almost now different (patched version is even\n> faster, but it seems to be just \"white noise\".\n>\n\nThis is not the worst case probably. In this patch the\nStartTransactionCommand is executed on every connection, although it is not\nnecessary - and for most use cases it will not be used.\n\nI did more tests - see attachments and I see a 5% slowdown - I don't think\nso it is acceptable for this case. This feature is nice, and for some users\nimportant, but only really few users can use it.\n\n┌────────────────┬─────────┬────────────┬─────────────┐\n│ test │ WITH LT │ LT ENABLED │ LT DISABLED │\n╞════════════════╪═════════╪════════════╪═════════════╡\n│ ro_constant_10 │ 539 │ 877 │ 905 │\n│ ro_index_10 │ 562 │ 808 │ 855 │\n│ ro_constant_50 │ 527 │ 843 │ 863 │\n│ ro_index_50 │ 544 │ 731 │ 742 │\n└────────────────┴─────────┴────────────┴─────────────┘\n(4 rows)\n\nI tested a performance of trigger (results of first column in table):\n\nCREATE OR REPLACE FUNCTION public.foo()\n RETURNS event_trigger\n LANGUAGE plpgsql\nAS $function$\nbegin\n if not pg_has_role(session_user, 'postgres', 'member') then\n raise exception 'you are not super user';\n end if;\nend;\n$function$;\n\nThere is an available snapshot in InitPostgres, and then there is possible\nto check if for the current database some connect event trigger exists.This\ncan reduce an overhead of this patch, when there are no logon triggers.\n\nI think so implemented and used names are ok, but for this feature the\nperformance impact should be really very minimal.\n\nThere is other small issue - missing tab-complete support for CREATE\nTRIGGER statement in psql\n\nRegards\n\nPavel\n\n\n> --\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>", "msg_date": "Thu, 10 Dec 2020 08:45:12 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 10.12.2020 10:45, Pavel Stehule wrote:\n>\n>\n> st 9. 12. 2020 v 14:28 odesílatel Konstantin Knizhnik \n> <k.knizhnik@postgrespro.ru <mailto:k.knizhnik@postgrespro.ru>> napsal:\n>\n>\n>\n> On 09.12.2020 15:34, Pavel Stehule wrote:\n>> Hi\n>>\n>> st 9. 12. 2020 v 13:17 odesílatel Greg Nancarrow\n>> <gregn4422@gmail.com <mailto:gregn4422@gmail.com>> napsal:\n>>\n>> On Tue, Dec 8, 2020 at 3:26 PM Pavel Stehule\n>> <pavel.stehule@gmail.com <mailto:pavel.stehule@gmail.com>> wrote:\n>> >\n>> >\n>> > There are two maybe generic questions?\n>> >\n>> > 1. Maybe we can introduce more generic GUC for all event\n>> triggers like disable_event_triggers? This GUC can be checked\n>> only by the database owner or super user. It can be an\n>> alternative ALTER TABLE DISABLE TRIGGER ALL. It can be\n>> protection against necessity to restart to single mode to\n>> repair the event trigger. I think so more generic solution is\n>> better than special disable_client_connection_trigger GUC.\n>> >\n>> > 2. I have no objection against client_connection. It is\n>> probably better for the mentioned purpose - possibility to\n>> block connection to database. Can be interesting, and I am\n>> not sure how much work it is to introduce the second event -\n>> session_start. This event should be started after connecting\n>> - so the exception there doesn't block connect, and should be\n>> started also after the new statement \"DISCARD SESSION\", that\n>> will be started automatically after DISCARD ALL. This feature\n>> should not be implemented in first step, but it can be a plan\n>> for support pooled connections\n>> >\n>>\n>> I've created a separate patch to address question (1), rather\n>> than\n>> include it in the main patch, which I've adjusted\n>> accordingly. I'll\n>> leave question (2) until another time, as you suggest.\n>> See the attached patches.\n>>\n>>\n>> I see two possible questions?\n>>\n>> 1. when you introduce this event, then the new hook is useless ?\n>>\n>> 2. what is a performance impact for users that want not to use\n>> this feature. What is a overhead of EventTriggerOnConnect and is\n>> possible to skip this step if database has not any event trigger\n>\n> As far as I understand this are questions to me rather than to Greg.\n> 1. Do you mean client_connection_hook? It is used to implement\n> this new event type. It can be also used for other purposes.\n>\n>\n> ok. I don't like it, but there are redundant hooks (against event \n> triggers) already.\n>\n>\n> 2. Connection overhead is quite large. Supporting on connect hook\n> requires traversal of event trigger relation. But this overhead is\n> negligible comparing with overhead of establishing connection. In\n> any case I did the following test (with local connection):\n>\n> pgbench -C -S -T 100 -P 1 -M prepared postgres\n>\n> without this patch:\n> tps = 424.287889 (including connections establishing)\n> tps = 952.911068 (excluding connections establishing)\n>\n> with this patch (but without any connection trigger defined):\n> tps = 434.642947 (including connections establishing)\n> tps = 995.525383 (excluding connections establishing)\n>\n> As you can see - there is almost now different (patched version is\n> even faster, but it seems to be just \"white noise\".\n>\n>\n> This is not the worst case probably. In this patch the \n> StartTransactionCommand is executed on every connection, although it \n> is not necessary - and for most use cases it will not be used.\n>\n> I did more tests - see attachments and I see a 5% slowdown - I don't \n> think so it is acceptable for this case. This feature is nice, and for \n> some users important, but only really few users can use it.\n>\n> ┌────────────────┬─────────┬────────────┬─────────────┐\n> │      test      │ WITH LT │ LT ENABLED │ LT DISABLED │\n> ╞════════════════╪═════════╪════════════╪═════════════╡\n> │ ro_constant_10 │     539 │        877 │         905 │\n> │ ro_index_10    │     562 │        808 │         855 │\n> │ ro_constant_50 │     527 │        843 │         863 │\n> │ ro_index_50    │     544 │        731 │         742 │\n> └────────────────┴─────────┴────────────┴─────────────┘\n> (4 rows)\n>\n> I tested a performance of trigger (results of first column in table):\n>\n> CREATE OR REPLACE FUNCTION public.foo()\n>  RETURNS event_trigger\n>  LANGUAGE plpgsql\n> AS $function$\n> begin\n>   if not pg_has_role(session_user, 'postgres', 'member') then\n>     raise exception 'you are not super user';\n>   end if;\n> end;\n> $function$;\n>\n> There is an available snapshot in InitPostgres, and then there is \n> possible to check if for the current database some connect event \n> trigger exists.This can reduce an overhead of this patch, when there \n> are no logon triggers.\n>\n> I think so implemented and used names are ok, but for this feature the \n> performance impact should be really very minimal.\n>\n> There is other small issue - missing tab-complete support for CREATE \n> TRIGGER statement in psql\n>\n> Regards\n>\n> Pavel\n>\n\nUnfortunately I was not able to reproduce your results.\nI just tried the case \"select 1\" because for this trivial query the \noverhead of session hooks should be the largest.\nIn my case variation of results was large enough.\nDid you try to run test multiple times?\n\npgbench -j 2 -c 10 --connect -f test-ro.sql -T 60 -n postgres\n\ndisable_event_triggers = off\ntps = 1812.250463 (including connections establishing)\ntps = 2256.285712 (excluding connections establishing)\n\ntps = 1838.107242 (including connections establishing)\ntps = 2288.507668 (excluding connections establishing)\n\ntps = 1830.879302 (including connections establishing)\ntps = 2279.302553 (excluding connections establishing)\n\n\ndisable_event_triggers = on\ntps = 1858.328717 (including connections establishing)\ntps = 2313.661689 (excluding connections establishing)\n\ntps = 1832.932960 (including connections establishing)\ntps = 2282.074346 (excluding connections establishing)\n\ntps = 1868.908521 (including connections establishing)\ntps = 2326.559150 (excluding connections establishing)\n\n\nI tried to increase run time to 1000 seconds.\nResults are the following:\n\ndisable_event_triggers = off\ntps = 1813.587876 (including connections establishing)\ntps = 2257.844703 (excluding connections establishing)\n\ndisable_event_triggers = on\ntps = 1838.107242 (including connections establishing)\ntps = 2288.507668 (excluding connections establishing)\n\nSo the difference on this extreme case is 1%.\n\nI tried your suggestion and move client_connection_hook invocation to \npostinit.c\nIt slightly improve performance:\n\ntps = 1828.446959 (including connections establishing)\ntps = 2276.142972 (excluding connections establishing)\n\nSo result is somewhere in the middle, because it allows to eliminate \noverhead of\nstarting transaction or taking snapshots but not of lookup through \npg_event_trigger table (although it it empty).\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n\n\n\n\n\n\nOn 10.12.2020 10:45, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\n\nst 9. 12. 2020 v 14:28\n odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n \n\nOn 09.12.2020 15:34, Pavel Stehule wrote:\n\n\n\nHi\n\n\n\nst 9. 12. 2020\n v 13:17 odesílatel Greg Nancarrow <gregn4422@gmail.com>\n napsal:\n\nOn Tue, Dec 8,\n 2020 at 3:26 PM Pavel Stehule <pavel.stehule@gmail.com>\n wrote:\n >\n >\n > There are two maybe generic questions?\n >\n > 1. Maybe we can introduce more generic GUC\n for all event triggers like\n disable_event_triggers? This GUC can be checked\n only by the database owner or super user. It can\n be an alternative ALTER TABLE DISABLE TRIGGER ALL.\n It can be protection against necessity to restart\n to single mode to repair the event trigger. I\n think so more generic solution is better than\n special disable_client_connection_trigger GUC.\n >\n > 2. I have no objection against\n client_connection. It is probably better for the\n mentioned purpose - possibility to block\n connection to database. Can be interesting, and I\n am not sure how much work it is to introduce the\n second event - session_start. This event should be\n started after connecting - so the exception there\n doesn't block connect, and should be started also\n after the new statement \"DISCARD SESSION\", that\n will be started automatically after DISCARD ALL. \n This feature should not be implemented in first\n step, but it can be a plan for support pooled\n connections\n >\n\n I've created a separate patch to address question\n (1), rather than\n include it in the main patch, which I've adjusted\n accordingly. I'll\n leave question (2) until another time, as you\n suggest.\n See the attached patches.\n\n\n\nI see two possible questions?\n\n\n 1. when you introduce this event, then the new\n hook is useless ?\n\n\n2. what is a performance impact for users that\n want not to use this feature. What is a overhead\n of EventTriggerOnConnect and is possible to skip\n this step if database has not any event trigger\n\n\n\n\n As far as I understand this are questions to me rather\n than to Greg.\n 1. Do you mean client_connection_hook? It is used to\n implement this new event type. It can be also used for\n other purposes.\n\n\n\n\nok. I don't like it, but there are redundant hooks\n (against event triggers) already.  \n\n\n\n \n\n\n 2. Connection overhead is quite\n large. Supporting on connect hook requires traversal of\n event trigger relation. But this overhead is negligible\n comparing with overhead of establishing connection. In any\n case I did the following test (with local connection):\n\n pgbench -C -S -T 100 -P 1 -M prepared postgres\n\n without this patch: \n tps = 424.287889 (including connections establishing)\n tps = 952.911068 (excluding connections establishing)\n\n with this patch (but without any connection trigger\n defined):\n tps = 434.642947 (including connections establishing)\n tps = 995.525383 (excluding connections establishing)\n\n As you can see - there is almost now different (patched\n version is even faster, but it seems to be just \"white\n noise\".\n\n\n\n\n\nThis is not the worst case probably. In\n this patch the StartTransactionCommand is executed on every\n connection, although it is not necessary - and for most use\n cases it will not be used. \n\n\n\nI did more tests - see attachments and\n I see a 5% slowdown - I don't think so it is acceptable for\n this case. This feature is nice, and for some users important,\n but only really few users can use it.\n\n\n┌────────────────┬─────────┬────────────┬─────────────┐\n │      test      │ WITH LT │ LT ENABLED │ LT DISABLED │\n ╞════════════════╪═════════╪════════════╪═════════════╡\n │ ro_constant_10 │     539 │        877 │         905 │\n │ ro_index_10    │     562 │        808 │         855 │\n │ ro_constant_50 │     527 │        843 │         863 │\n │ ro_index_50    │     544 │        731 │         742 │\n └────────────────┴─────────┴────────────┴─────────────┘\n (4 rows)\n\n\n\n\nI tested a performance of trigger (results of first\n column in table):\n\n\n\nCREATE OR REPLACE\n FUNCTION public.foo()\n  RETURNS event_trigger\n  LANGUAGE plpgsql\n AS $function$\n begin\n   if not pg_has_role(session_user, 'postgres', 'member')\n then\n     raise exception 'you are not super user';\n   end if;\n end;\n $function$;\n\n\nThere is an available snapshot in InitPostgres, and then\n there is possible to check if for the current database some\n connect event trigger exists.This can reduce an overhead of\n this patch, when there are no logon triggers.\n\n\nI think so implemented and used names are ok, but for\n this feature the performance impact should be really very\n minimal.\n\n\n\nThere is other small issue - missing tab-complete support\n for CREATE TRIGGER statement in psql\n\n\nRegards\n\n\nPavel\n\n\n\n\n\n Unfortunately I was not able to reproduce your results. \n I just tried the case \"select 1\" because for this trivial query the\n overhead of session hooks should be the largest.\n In my case variation of results was large enough.\n Did you try to run test multiple times? \n\n pgbench -j 2 -c 10 --connect -f test-ro.sql -T 60 -n postgres\n\n disable_event_triggers = off\n tps = 1812.250463 (including connections establishing)\n tps = 2256.285712 (excluding connections establishing)\n\n tps = 1838.107242 (including connections establishing)\n tps = 2288.507668 (excluding connections establishing)\n\n tps = 1830.879302 (including connections establishing)\n tps = 2279.302553 (excluding connections establishing)\n\n\n disable_event_triggers = on\n tps = 1858.328717 (including connections establishing)\n tps = 2313.661689 (excluding connections establishing)\n\n tps = 1832.932960 (including connections establishing)\n tps = 2282.074346 (excluding connections establishing)\n\n tps = 1868.908521 (including connections establishing)\n tps = 2326.559150 (excluding connections establishing)\n\n\n I tried to increase run time to 1000 seconds.\n Results are the following:\n\n disable_event_triggers = off\n tps = 1813.587876 (including connections establishing)\n tps = 2257.844703 (excluding connections establishing)\n\n disable_event_triggers = on\n tps = 1838.107242 (including connections establishing)\n tps = 2288.507668 (excluding connections establishing)\n\n So the difference on this extreme case is 1%.\n\n I tried your suggestion and move client_connection_hook invocation\n to postinit.c\n It slightly improve performance:\n\n tps = 1828.446959 (including connections establishing)\n tps = 2276.142972 (excluding connections establishing)\n\n So result is somewhere in the middle, because it allows to eliminate\n overhead of\n starting transaction or taking snapshots but not of lookup through\n pg_event_trigger table (although it it empty).\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Thu, 10 Dec 2020 16:03:14 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "čt 10. 12. 2020 v 14:03 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 10.12.2020 10:45, Pavel Stehule wrote:\n>\n>\n>\n> st 9. 12. 2020 v 14:28 odesílatel Konstantin Knizhnik <\n> k.knizhnik@postgrespro.ru> napsal:\n>\n>>\n>>\n>> On 09.12.2020 15:34, Pavel Stehule wrote:\n>>\n>> Hi\n>>\n>> st 9. 12. 2020 v 13:17 odesílatel Greg Nancarrow <gregn4422@gmail.com>\n>> napsal:\n>>\n>>> On Tue, Dec 8, 2020 at 3:26 PM Pavel Stehule <pavel.stehule@gmail.com>\n>>> wrote:\n>>> >\n>>> >\n>>> > There are two maybe generic questions?\n>>> >\n>>> > 1. Maybe we can introduce more generic GUC for all event triggers like\n>>> disable_event_triggers? This GUC can be checked only by the database owner\n>>> or super user. It can be an alternative ALTER TABLE DISABLE TRIGGER ALL. It\n>>> can be protection against necessity to restart to single mode to repair the\n>>> event trigger. I think so more generic solution is better than special\n>>> disable_client_connection_trigger GUC.\n>>> >\n>>> > 2. I have no objection against client_connection. It is probably\n>>> better for the mentioned purpose - possibility to block connection to\n>>> database. Can be interesting, and I am not sure how much work it is to\n>>> introduce the second event - session_start. This event should be started\n>>> after connecting - so the exception there doesn't block connect, and should\n>>> be started also after the new statement \"DISCARD SESSION\", that will be\n>>> started automatically after DISCARD ALL. This feature should not be\n>>> implemented in first step, but it can be a plan for support pooled\n>>> connections\n>>> >\n>>>\n>>> I've created a separate patch to address question (1), rather than\n>>> include it in the main patch, which I've adjusted accordingly. I'll\n>>> leave question (2) until another time, as you suggest.\n>>> See the attached patches.\n>>>\n>>\n>> I see two possible questions?\n>>\n>> 1. when you introduce this event, then the new hook is useless ?\n>>\n>> 2. what is a performance impact for users that want not to use this\n>> feature. What is a overhead of EventTriggerOnConnect and is possible to\n>> skip this step if database has not any event trigger\n>>\n>>\n>> As far as I understand this are questions to me rather than to Greg.\n>> 1. Do you mean client_connection_hook? It is used to implement this new\n>> event type. It can be also used for other purposes.\n>>\n>\n> ok. I don't like it, but there are redundant hooks (against event\n> triggers) already.\n>\n>\n> 2. Connection overhead is quite large. Supporting on connect hook requires\n>> traversal of event trigger relation. But this overhead is negligible\n>> comparing with overhead of establishing connection. In any case I did the\n>> following test (with local connection):\n>>\n>> pgbench -C -S -T 100 -P 1 -M prepared postgres\n>>\n>> without this patch:\n>> tps = 424.287889 (including connections establishing)\n>> tps = 952.911068 (excluding connections establishing)\n>>\n>> with this patch (but without any connection trigger defined):\n>> tps = 434.642947 (including connections establishing)\n>> tps = 995.525383 (excluding connections establishing)\n>>\n>> As you can see - there is almost now different (patched version is even\n>> faster, but it seems to be just \"white noise\".\n>>\n>\n> This is not the worst case probably. In this patch the\n> StartTransactionCommand is executed on every connection, although it is not\n> necessary - and for most use cases it will not be used.\n>\n> I did more tests - see attachments and I see a 5% slowdown - I don't think\n> so it is acceptable for this case. This feature is nice, and for some users\n> important, but only really few users can use it.\n>\n> ┌────────────────┬─────────┬────────────┬─────────────┐\n> │ test │ WITH LT │ LT ENABLED │ LT DISABLED │\n> ╞════════════════╪═════════╪════════════╪═════════════╡\n> │ ro_constant_10 │ 539 │ 877 │ 905 │\n> │ ro_index_10 │ 562 │ 808 │ 855 │\n> │ ro_constant_50 │ 527 │ 843 │ 863 │\n> │ ro_index_50 │ 544 │ 731 │ 742 │\n> └────────────────┴─────────┴────────────┴─────────────┘\n> (4 rows)\n>\n> I tested a performance of trigger (results of first column in table):\n>\n> CREATE OR REPLACE FUNCTION public.foo()\n> RETURNS event_trigger\n> LANGUAGE plpgsql\n> AS $function$\n> begin\n> if not pg_has_role(session_user, 'postgres', 'member') then\n> raise exception 'you are not super user';\n> end if;\n> end;\n> $function$;\n>\n> There is an available snapshot in InitPostgres, and then there is possible\n> to check if for the current database some connect event trigger exists.This\n> can reduce an overhead of this patch, when there are no logon triggers.\n>\n> I think so implemented and used names are ok, but for this feature the\n> performance impact should be really very minimal.\n>\n> There is other small issue - missing tab-complete support for CREATE\n> TRIGGER statement in psql\n>\n> Regards\n>\n> Pavel\n>\n>\n> Unfortunately I was not able to reproduce your results.\n> I just tried the case \"select 1\" because for this trivial query the\n> overhead of session hooks should be the largest.\n> In my case variation of results was large enough.\n> Did you try to run test multiple times?\n>\n> pgbench -j 2 -c 10 --connect -f test-ro.sql -T 60 -n postgres\n>\n> disable_event_triggers = off\n> tps = 1812.250463 (including connections establishing)\n> tps = 2256.285712 (excluding connections establishing)\n>\n> tps = 1838.107242 (including connections establishing)\n> tps = 2288.507668 (excluding connections establishing)\n>\n> tps = 1830.879302 (including connections establishing)\n> tps = 2279.302553 (excluding connections establishing)\n>\n>\n> disable_event_triggers = on\n> tps = 1858.328717 (including connections establishing)\n> tps = 2313.661689 (excluding connections establishing)\n>\n> tps = 1832.932960 (including connections establishing)\n> tps = 2282.074346 (excluding connections establishing)\n>\n> tps = 1868.908521 (including connections establishing)\n> tps = 2326.559150 (excluding connections establishing)\n>\n>\n> I tried to increase run time to 1000 seconds.\n> Results are the following:\n>\n> disable_event_triggers = off\n> tps = 1813.587876 (including connections establishing)\n> tps = 2257.844703 (excluding connections establishing)\n>\n> disable_event_triggers = on\n> tps = 1838.107242 (including connections establishing)\n> tps = 2288.507668 (excluding connections establishing)\n>\n> So the difference on this extreme case is 1%.\n>\n\nyou have a stronger CPU (2x), and probably you are hitting different\nbottleneck or maybe some other is wrong. I can recheck it and I can attach\nprofiles.\n\n\n\n> I tried your suggestion and move client_connection_hook invocation to\n> postinit.c\n> It slightly improve performance:\n>\n> tps = 1828.446959 (including connections establishing)\n> tps = 2276.142972 (excluding connections establishing)\n>\n> So result is somewhere in the middle, because it allows to eliminate\n> overhead of\n> starting transaction or taking snapshots but not of lookup through\n> pg_event_trigger table (although it it empty).\n>\n\nMy idea was a little bit different. Inside postinit initialize some global\nvariables with info if there are event triggers or not. And later you can\nuse this variable to start transactions and other things.\n\nThere will be two access to pg_event_trigger, but it can eliminate useless\nand probably more expensive start_transaction and end_transaction.\n\nRegards\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 10. 12. 2020 v 14:03 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n\n\nOn 10.12.2020 10:45, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\nst 9. 12. 2020 v 14:28\n odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n \n\nOn 09.12.2020 15:34, Pavel Stehule wrote:\n\n\n\nHi\n\n\n\nst 9. 12. 2020\n v 13:17 odesílatel Greg Nancarrow <gregn4422@gmail.com>\n napsal:\n\nOn Tue, Dec 8,\n 2020 at 3:26 PM Pavel Stehule <pavel.stehule@gmail.com>\n wrote:\n >\n >\n > There are two maybe generic questions?\n >\n > 1. Maybe we can introduce more generic GUC\n for all event triggers like\n disable_event_triggers? This GUC can be checked\n only by the database owner or super user. It can\n be an alternative ALTER TABLE DISABLE TRIGGER ALL.\n It can be protection against necessity to restart\n to single mode to repair the event trigger. I\n think so more generic solution is better than\n special disable_client_connection_trigger GUC.\n >\n > 2. I have no objection against\n client_connection. It is probably better for the\n mentioned purpose - possibility to block\n connection to database. Can be interesting, and I\n am not sure how much work it is to introduce the\n second event - session_start. This event should be\n started after connecting - so the exception there\n doesn't block connect, and should be started also\n after the new statement \"DISCARD SESSION\", that\n will be started automatically after DISCARD ALL. \n This feature should not be implemented in first\n step, but it can be a plan for support pooled\n connections\n >\n\n I've created a separate patch to address question\n (1), rather than\n include it in the main patch, which I've adjusted\n accordingly. I'll\n leave question (2) until another time, as you\n suggest.\n See the attached patches.\n\n\n\nI see two possible questions?\n\n\n 1. when you introduce this event, then the new\n hook is useless ?\n\n\n2. what is a performance impact for users that\n want not to use this feature. What is a overhead\n of EventTriggerOnConnect and is possible to skip\n this step if database has not any event trigger\n\n\n\n\n As far as I understand this are questions to me rather\n than to Greg.\n 1. Do you mean client_connection_hook? It is used to\n implement this new event type. It can be also used for\n other purposes.\n\n\n\n\nok. I don't like it, but there are redundant hooks\n (against event triggers) already.  \n\n\n\n \n\n\n 2. Connection overhead is quite\n large. Supporting on connect hook requires traversal of\n event trigger relation. But this overhead is negligible\n comparing with overhead of establishing connection. In any\n case I did the following test (with local connection):\n\n pgbench -C -S -T 100 -P 1 -M prepared postgres\n\n without this patch: \n tps = 424.287889 (including connections establishing)\n tps = 952.911068 (excluding connections establishing)\n\n with this patch (but without any connection trigger\n defined):\n tps = 434.642947 (including connections establishing)\n tps = 995.525383 (excluding connections establishing)\n\n As you can see - there is almost now different (patched\n version is even faster, but it seems to be just \"white\n noise\".\n\n\n\n\n\nThis is not the worst case probably. In\n this patch the StartTransactionCommand is executed on every\n connection, although it is not necessary - and for most use\n cases it will not be used. \n\n\n\nI did more tests - see attachments and\n I see a 5% slowdown - I don't think so it is acceptable for\n this case. This feature is nice, and for some users important,\n but only really few users can use it.\n\n\n┌────────────────┬─────────┬────────────┬─────────────┐\n │      test      │ WITH LT │ LT ENABLED │ LT DISABLED │\n ╞════════════════╪═════════╪════════════╪═════════════╡\n │ ro_constant_10 │     539 │        877 │         905 │\n │ ro_index_10    │     562 │        808 │         855 │\n │ ro_constant_50 │     527 │        843 │         863 │\n │ ro_index_50    │     544 │        731 │         742 │\n └────────────────┴─────────┴────────────┴─────────────┘\n (4 rows)\n\n\n\n\nI tested a performance of trigger (results of first\n column in table):\n\n\n\nCREATE OR REPLACE\n FUNCTION public.foo()\n  RETURNS event_trigger\n  LANGUAGE plpgsql\n AS $function$\n begin\n   if not pg_has_role(session_user, 'postgres', 'member')\n then\n     raise exception 'you are not super user';\n   end if;\n end;\n $function$;\n\n\nThere is an available snapshot in InitPostgres, and then\n there is possible to check if for the current database some\n connect event trigger exists.This can reduce an overhead of\n this patch, when there are no logon triggers.\n\n\nI think so implemented and used names are ok, but for\n this feature the performance impact should be really very\n minimal.\n\n\n\nThere is other small issue - missing tab-complete support\n for CREATE TRIGGER statement in psql\n\n\nRegards\n\n\nPavel\n\n\n\n\n\n Unfortunately I was not able to reproduce your results. \n I just tried the case \"select 1\" because for this trivial query the\n overhead of session hooks should be the largest.\n In my case variation of results was large enough.\n Did you try to run test multiple times? \n\n pgbench -j 2 -c 10 --connect -f test-ro.sql -T 60 -n postgres\n\n disable_event_triggers = off\n tps = 1812.250463 (including connections establishing)\n tps = 2256.285712 (excluding connections establishing)\n\n tps = 1838.107242 (including connections establishing)\n tps = 2288.507668 (excluding connections establishing)\n\n tps = 1830.879302 (including connections establishing)\n tps = 2279.302553 (excluding connections establishing)\n\n\n disable_event_triggers = on\n tps = 1858.328717 (including connections establishing)\n tps = 2313.661689 (excluding connections establishing)\n\n tps = 1832.932960 (including connections establishing)\n tps = 2282.074346 (excluding connections establishing)\n\n tps = 1868.908521 (including connections establishing)\n tps = 2326.559150 (excluding connections establishing)\n\n\n I tried to increase run time to 1000 seconds.\n Results are the following:\n\n disable_event_triggers = off\n tps = 1813.587876 (including connections establishing)\n tps = 2257.844703 (excluding connections establishing)\n\n disable_event_triggers = on\n tps = 1838.107242 (including connections establishing)\n tps = 2288.507668 (excluding connections establishing)\n\n So the difference on this extreme case is 1%.you have a stronger CPU (2x), and probably you are hitting different bottleneck or maybe some other is wrong. I can recheck it and I can attach profiles. \n\n I tried your suggestion and move client_connection_hook invocation\n to postinit.c\n It slightly improve performance:\n\n tps = 1828.446959 (including connections establishing)\n tps = 2276.142972 (excluding connections establishing)\n\n So result is somewhere in the middle, because it allows to eliminate\n overhead of\n starting transaction or taking snapshots but not of lookup through\n pg_event_trigger table (although it it empty).My idea was a little bit different. Inside postinit initialize some global variables with info if there are event triggers or not. And later you can use this variable to start transactions and  other things.There will be two access to pg_event_trigger, but it can eliminate useless and probably more expensive start_transaction and end_transaction.RegardsPavel\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Thu, 10 Dec 2020 16:12:49 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 10.12.2020 18:12, Pavel Stehule wrote:\n>\n> My idea was a little bit different. Inside postinit initialize some \n> global variables with info if there are event triggers or not. And \n> later you can use this variable to start transactions and  other things.\n>\n> There will be two access to pg_event_trigger, but it can eliminate \n> useless and probably more expensive start_transaction and end_transaction.\n>\n\n\nDo you mean some variable in shared memory or GUCs?\nIt was my first idea - to use some flag in shared memory to make it \npossible fast check that there are not event triggers.\nBut this flag should be sent per database. May be I missed something, \nbut there is no any per-database shared memory  data structure in Postgres.\nCertainly it is possible to organize some hash db->event_info, but it \nmakes this patch several times more complex.\n\n From my point of view it is better to have separate GUC disabling just \nclient connection events and switch it on by default.\nSo only those who need this events with switch it on, other users will \nnot pay any extra cost for it.\n\n\n\n\n\n\n\n\n\nOn 10.12.2020 18:12, Pavel Stehule\n wrote:\n\n\n\n\n\nMy idea was a little bit different. Inside postinit\n initialize some global variables with info if there are\n event triggers or not. And later you can use this variable\n to start transactions and  other things.\n\n\nThere will be two access to pg_event_trigger, but it can\n eliminate useless and probably more expensive\n start_transaction and end_transaction.\n\n\n\n\n\n\n Do you mean some variable in shared memory or GUCs?\n It was my first idea - to use some flag in shared memory to make it\n possible fast check that there are not event triggers.\n But this flag should be sent per database. May be I missed\n something, but there is no any per-database shared memory  data\n structure in Postgres.\n Certainly it is possible to organize some hash db->event_info,\n but it makes this patch several times more complex.\n\n From my point of view it is better to have separate GUC disabling\n just client connection events and switch it on by default.\n So only those who need this events with switch it on, other users\n will not pay any extra cost for it.", "msg_date": "Thu, 10 Dec 2020 18:48:49 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "čt 10. 12. 2020 v 16:48 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 10.12.2020 18:12, Pavel Stehule wrote:\n>\n>\n> My idea was a little bit different. Inside postinit initialize some global\n> variables with info if there are event triggers or not. And later you can\n> use this variable to start transactions and other things.\n>\n> There will be two access to pg_event_trigger, but it can eliminate useless\n> and probably more expensive start_transaction and end_transaction.\n>\n>\n>\n> Do you mean some variable in shared memory or GUCs?\n> It was my first idea - to use some flag in shared memory to make it\n> possible fast check that there are not event triggers.\n> But this flag should be sent per database. May be I missed something, but\n> there is no any per-database shared memory data structure in Postgres.\n> Certainly it is possible to organize some hash db->event_info, but it\n> makes this patch several times more complex.\n>\n\nMy idea was a little bit different - just inside process initialization,\nchecking existence of event triggers, and later when it is necessary to\nstart a transaction for trigger execution. This should to reduce useless\nempty transaction,\n\nI am sure this is a problem on computers with slower CPU s, although I have\nI7, but because this feature is usually unused, then the performance impact\nshould be minimal every time.\n\n\n\n>\n> From my point of view it is better to have separate GUC disabling just\n> client connection events and switch it on by default.\n> So only those who need this events with switch it on, other users will not\n> pay any extra cost for it.\n>\n\nIt can work, but this design is not user friendly. The significant\nbottleneck should be forking new processes, and check of content some\nusually very small tables should be invisible. So if there is a possible\nway to implement some feature that can be enabled by default, then we\nshould go this way. It can be pretty unfriendly if somebody writes a logon\ntrigger and it will not work by default without any warning.\n\nWhen I tested last patch I found a problem (I have disabled assertions due\nperformance testing)\n\ncreate role xx login;\nalter system set disable_event_triggers to on; -- better should be positive\nform - enable_event_triggers to on, off\nselect pg_reload_conf();\n\npsql -U xx\n\nThread 2.1 \"postmaster\" received signal SIGSEGV, Segmentation fault.\n[Switching to Thread 0x7f2bff438ec0 (LWP 827497)]\nResourceOwnerEnlargeCatCacheRefs (owner=0x0) at resowner.c:1025\n1025 ResourceArrayEnlarge(&(owner->catrefarr));\n(gdb) bt\n#0 ResourceOwnerEnlargeCatCacheRefs (owner=0x0) at resowner.c:1025\n#1 0x00000000008a70f8 in SearchCatCacheInternal (cache=<optimized out>,\nnkeys=nkeys@entry=1, v1=v1@entry=13836, v2=v2@entry=0,\n v3=v3@entry=0, v4=v4@entry=0) at catcache.c:1273\n#2 0x00000000008a7575 in SearchCatCache1 (cache=<optimized out>,\nv1=v1@entry=13836) at catcache.c:1167\n#3 0x00000000008b7f80 in SearchSysCache1 (cacheId=cacheId@entry=21,\nkey1=key1@entry=13836) at syscache.c:1122\n#4 0x00000000005939cd in pg_database_ownercheck (db_oid=13836,\nroleid=16387) at aclchk.c:5114\n#5 0x0000000000605b42 in EventTriggersDisabled () at event_trigger.c:650\n#6 EventTriggerOnConnect () at event_trigger.c:839\n#7 0x00000000007b46d7 in PostgresMain (argc=argc@entry=1,\nargv=argv@entry=0x7ffdd6256080,\ndbname=<optimized out>,\n username=0xf82508 \"tom\") at postgres.c:4021\n#8 0x0000000000741afd in BackendRun (port=<optimized out>, port=<optimized\nout>) at postmaster.c:4490\n#9 BackendStartup (port=<optimized out>) at postmaster.c:4212\n#10 ServerLoop () at postmaster.c:1729\n#11 0x0000000000742881 in PostmasterMain (argc=argc@entry=3,\nargv=argv@entry=0xf44d00)\nat postmaster.c:1401\n#12 0x00000000004f1ff7 in main (argc=3, argv=0xf44d00) at main.c:209\n\nI checked profiles, and although there is significant slowdown when there\nis one login trigger, it was not related to plpgsql.\n\nThere is big overhead of\n\n 8,98% postmaster postgres [.] guc_name_compare\n\nMaybe EventTriggerInvoke is not well optimized for very frequent execution.\nOverhead of plpgsql is less than 0.1%, although there is significant\nslowdown (when a very simple logon trigger is executed).\n\nRegards\n\nPavel\n\nčt 10. 12. 2020 v 16:48 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n\n\nOn 10.12.2020 18:12, Pavel Stehule\n wrote:\n\n\n\n\nMy idea was a little bit different. Inside postinit\n initialize some global variables with info if there are\n event triggers or not. And later you can use this variable\n to start transactions and  other things.\n\n\nThere will be two access to pg_event_trigger, but it can\n eliminate useless and probably more expensive\n start_transaction and end_transaction.\n\n\n\n\n\n\n Do you mean some variable in shared memory or GUCs?\n It was my first idea - to use some flag in shared memory to make it\n possible fast check that there are not event triggers.\n But this flag should be sent per database. May be I missed\n something, but there is no any per-database shared memory  data\n structure in Postgres.\n Certainly it is possible to organize some hash db->event_info,\n but it makes this patch several times more complex.My idea was a little bit different - just inside process initialization, checking existence of event triggers, and later when it is necessary to start a transaction for trigger execution. This should to reduce useless empty transaction, I am sure this is a problem on computers with slower CPU s, although I have I7, but because this feature is usually unused, then the performance impact should be minimal every time.  \n\n From my point of view it is better to have separate GUC disabling\n just client connection events and switch it on by default.\n So only those who need this events with switch it on, other users\n will not pay any extra cost for it.It can work, but this design is not user friendly.  The significant bottleneck should be forking new processes, and check of content some usually very small tables should be invisible. So if there is a possible way to implement some feature that can be enabled by default, then we should go this way. It can be pretty unfriendly if somebody writes a logon trigger and it will not work by default without any warning. When I tested last patch I found a problem (I have disabled assertions due performance testing)create role xx login;alter system set disable_event_triggers to on; -- better should be positive form - enable_event_triggers to on, offselect pg_reload_conf();psql -U xxThread 2.1 \"postmaster\" received signal SIGSEGV, Segmentation fault.[Switching to Thread 0x7f2bff438ec0 (LWP 827497)]ResourceOwnerEnlargeCatCacheRefs (owner=0x0) at resowner.c:10251025\t\tResourceArrayEnlarge(&(owner->catrefarr));(gdb) bt#0  ResourceOwnerEnlargeCatCacheRefs (owner=0x0) at resowner.c:1025#1  0x00000000008a70f8 in SearchCatCacheInternal (cache=<optimized out>, nkeys=nkeys@entry=1, v1=v1@entry=13836, v2=v2@entry=0,     v3=v3@entry=0, v4=v4@entry=0) at catcache.c:1273#2  0x00000000008a7575 in SearchCatCache1 (cache=<optimized out>, v1=v1@entry=13836) at catcache.c:1167#3  0x00000000008b7f80 in SearchSysCache1 (cacheId=cacheId@entry=21, key1=key1@entry=13836) at syscache.c:1122#4  0x00000000005939cd in pg_database_ownercheck (db_oid=13836, roleid=16387) at aclchk.c:5114#5  0x0000000000605b42 in EventTriggersDisabled () at event_trigger.c:650#6  EventTriggerOnConnect () at event_trigger.c:839#7  0x00000000007b46d7 in PostgresMain (argc=argc@entry=1, argv=argv@entry=0x7ffdd6256080, dbname=<optimized out>,     username=0xf82508 \"tom\") at postgres.c:4021#8  0x0000000000741afd in BackendRun (port=<optimized out>, port=<optimized out>) at postmaster.c:4490#9  BackendStartup (port=<optimized out>) at postmaster.c:4212#10 ServerLoop () at postmaster.c:1729#11 0x0000000000742881 in PostmasterMain (argc=argc@entry=3, argv=argv@entry=0xf44d00) at postmaster.c:1401#12 0x00000000004f1ff7 in main (argc=3, argv=0xf44d00) at main.c:209I checked profiles, and although there is significant slowdown when there is one login trigger, it was not related to plpgsql. There is big overhead of    8,98%  postmaster  postgres              [.] guc_name_compare Maybe EventTriggerInvoke is not well optimized for very frequent execution. Overhead of plpgsql is less than 0.1%, although there is significant slowdown (when a very simple logon trigger is executed).RegardsPavel", "msg_date": "Thu, 10 Dec 2020 19:09:07 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "čt 10. 12. 2020 v 19:09 odesílatel Pavel Stehule <pavel.stehule@gmail.com>\nnapsal:\n\n>\n>\n> čt 10. 12. 2020 v 16:48 odesílatel Konstantin Knizhnik <\n> k.knizhnik@postgrespro.ru> napsal:\n>\n>>\n>>\n>> On 10.12.2020 18:12, Pavel Stehule wrote:\n>>\n>>\n>> My idea was a little bit different. Inside postinit initialize some\n>> global variables with info if there are event triggers or not. And later\n>> you can use this variable to start transactions and other things.\n>>\n>> There will be two access to pg_event_trigger, but it can eliminate\n>> useless and probably more expensive start_transaction and end_transaction.\n>>\n>>\n>>\n>> Do you mean some variable in shared memory or GUCs?\n>> It was my first idea - to use some flag in shared memory to make it\n>> possible fast check that there are not event triggers.\n>> But this flag should be sent per database. May be I missed something, but\n>> there is no any per-database shared memory data structure in Postgres.\n>> Certainly it is possible to organize some hash db->event_info, but it\n>> makes this patch several times more complex.\n>>\n>\n> My idea was a little bit different - just inside process initialization,\n> checking existence of event triggers, and later when it is necessary to\n> start a transaction for trigger execution. This should to reduce useless\n> empty transaction,\n>\n\nbut this information can be accessed via shared memory if it is necessary.\nProbably it doesn't need a special hash table. Maybe a special flag per\nprocess.\n\n\n> I am sure this is a problem on computers with slower CPU s, although I\n> have I7, but because this feature is usually unused, then the performance\n> impact should be minimal every time.\n>\n>\n>\n>>\n>> From my point of view it is better to have separate GUC disabling just\n>> client connection events and switch it on by default.\n>> So only those who need this events with switch it on, other users will\n>> not pay any extra cost for it.\n>>\n>\n> It can work, but this design is not user friendly. The significant\n> bottleneck should be forking new processes, and check of content some\n> usually very small tables should be invisible. So if there is a possible\n> way to implement some feature that can be enabled by default, then we\n> should go this way. It can be pretty unfriendly if somebody writes a logon\n> trigger and it will not work by default without any warning.\n>\n> When I tested last patch I found a problem (I have disabled assertions due\n> performance testing)\n>\n> create role xx login;\n> alter system set disable_event_triggers to on; -- better should be\n> positive form - enable_event_triggers to on, off\n> select pg_reload_conf();\n>\n> psql -U xx\n>\n> Thread 2.1 \"postmaster\" received signal SIGSEGV, Segmentation fault.\n> [Switching to Thread 0x7f2bff438ec0 (LWP 827497)]\n> ResourceOwnerEnlargeCatCacheRefs (owner=0x0) at resowner.c:1025\n> 1025 ResourceArrayEnlarge(&(owner->catrefarr));\n> (gdb) bt\n> #0 ResourceOwnerEnlargeCatCacheRefs (owner=0x0) at resowner.c:1025\n> #1 0x00000000008a70f8 in SearchCatCacheInternal (cache=<optimized out>,\n> nkeys=nkeys@entry=1, v1=v1@entry=13836, v2=v2@entry=0,\n> v3=v3@entry=0, v4=v4@entry=0) at catcache.c:1273\n> #2 0x00000000008a7575 in SearchCatCache1 (cache=<optimized out>,\n> v1=v1@entry=13836) at catcache.c:1167\n> #3 0x00000000008b7f80 in SearchSysCache1 (cacheId=cacheId@entry=21,\n> key1=key1@entry=13836) at syscache.c:1122\n> #4 0x00000000005939cd in pg_database_ownercheck (db_oid=13836,\n> roleid=16387) at aclchk.c:5114\n> #5 0x0000000000605b42 in EventTriggersDisabled () at event_trigger.c:650\n> #6 EventTriggerOnConnect () at event_trigger.c:839\n> #7 0x00000000007b46d7 in PostgresMain (argc=argc@entry=1, argv=argv@entry=0x7ffdd6256080,\n> dbname=<optimized out>,\n> username=0xf82508 \"tom\") at postgres.c:4021\n> #8 0x0000000000741afd in BackendRun (port=<optimized out>,\n> port=<optimized out>) at postmaster.c:4490\n> #9 BackendStartup (port=<optimized out>) at postmaster.c:4212\n> #10 ServerLoop () at postmaster.c:1729\n> #11 0x0000000000742881 in PostmasterMain (argc=argc@entry=3,\n> argv=argv@entry=0xf44d00) at postmaster.c:1401\n> #12 0x00000000004f1ff7 in main (argc=3, argv=0xf44d00) at main.c:209\n>\n> I checked profiles, and although there is significant slowdown when there\n> is one login trigger, it was not related to plpgsql.\n>\n> There is big overhead of\n>\n> 8,98% postmaster postgres [.] guc_name_compare\n>\n> Maybe EventTriggerInvoke is not well optimized for very frequent\n> execution. Overhead of plpgsql is less than 0.1%, although there is\n> significant slowdown (when a very simple logon trigger is executed).\n>\n> Regards\n>\n> Pavel\n>\n>\n>\n>\n\nčt 10. 12. 2020 v 19:09 odesílatel Pavel Stehule <pavel.stehule@gmail.com> napsal:čt 10. 12. 2020 v 16:48 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n\n\nOn 10.12.2020 18:12, Pavel Stehule\n wrote:\n\n\n\n\nMy idea was a little bit different. Inside postinit\n initialize some global variables with info if there are\n event triggers or not. And later you can use this variable\n to start transactions and  other things.\n\n\nThere will be two access to pg_event_trigger, but it can\n eliminate useless and probably more expensive\n start_transaction and end_transaction.\n\n\n\n\n\n\n Do you mean some variable in shared memory or GUCs?\n It was my first idea - to use some flag in shared memory to make it\n possible fast check that there are not event triggers.\n But this flag should be sent per database. May be I missed\n something, but there is no any per-database shared memory  data\n structure in Postgres.\n Certainly it is possible to organize some hash db->event_info,\n but it makes this patch several times more complex.My idea was a little bit different - just inside process initialization, checking existence of event triggers, and later when it is necessary to start a transaction for trigger execution. This should to reduce useless empty transaction, but this information can be accessed via shared memory if it is necessary. Probably it doesn't need a special hash table.  Maybe a special flag per process. I am sure this is a problem on computers with slower CPU s, although I have I7, but because this feature is usually unused, then the performance impact should be minimal every time.  \n\n From my point of view it is better to have separate GUC disabling\n just client connection events and switch it on by default.\n So only those who need this events with switch it on, other users\n will not pay any extra cost for it.It can work, but this design is not user friendly.  The significant bottleneck should be forking new processes, and check of content some usually very small tables should be invisible. So if there is a possible way to implement some feature that can be enabled by default, then we should go this way. It can be pretty unfriendly if somebody writes a logon trigger and it will not work by default without any warning. When I tested last patch I found a problem (I have disabled assertions due performance testing)create role xx login;alter system set disable_event_triggers to on; -- better should be positive form - enable_event_triggers to on, offselect pg_reload_conf();psql -U xxThread 2.1 \"postmaster\" received signal SIGSEGV, Segmentation fault.[Switching to Thread 0x7f2bff438ec0 (LWP 827497)]ResourceOwnerEnlargeCatCacheRefs (owner=0x0) at resowner.c:10251025\t\tResourceArrayEnlarge(&(owner->catrefarr));(gdb) bt#0  ResourceOwnerEnlargeCatCacheRefs (owner=0x0) at resowner.c:1025#1  0x00000000008a70f8 in SearchCatCacheInternal (cache=<optimized out>, nkeys=nkeys@entry=1, v1=v1@entry=13836, v2=v2@entry=0,     v3=v3@entry=0, v4=v4@entry=0) at catcache.c:1273#2  0x00000000008a7575 in SearchCatCache1 (cache=<optimized out>, v1=v1@entry=13836) at catcache.c:1167#3  0x00000000008b7f80 in SearchSysCache1 (cacheId=cacheId@entry=21, key1=key1@entry=13836) at syscache.c:1122#4  0x00000000005939cd in pg_database_ownercheck (db_oid=13836, roleid=16387) at aclchk.c:5114#5  0x0000000000605b42 in EventTriggersDisabled () at event_trigger.c:650#6  EventTriggerOnConnect () at event_trigger.c:839#7  0x00000000007b46d7 in PostgresMain (argc=argc@entry=1, argv=argv@entry=0x7ffdd6256080, dbname=<optimized out>,     username=0xf82508 \"tom\") at postgres.c:4021#8  0x0000000000741afd in BackendRun (port=<optimized out>, port=<optimized out>) at postmaster.c:4490#9  BackendStartup (port=<optimized out>) at postmaster.c:4212#10 ServerLoop () at postmaster.c:1729#11 0x0000000000742881 in PostmasterMain (argc=argc@entry=3, argv=argv@entry=0xf44d00) at postmaster.c:1401#12 0x00000000004f1ff7 in main (argc=3, argv=0xf44d00) at main.c:209I checked profiles, and although there is significant slowdown when there is one login trigger, it was not related to plpgsql. There is big overhead of    8,98%  postmaster  postgres              [.] guc_name_compare Maybe EventTriggerInvoke is not well optimized for very frequent execution. Overhead of plpgsql is less than 0.1%, although there is significant slowdown (when a very simple logon trigger is executed).RegardsPavel", "msg_date": "Fri, 11 Dec 2020 07:59:57 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 10.12.2020 21:09, Pavel Stehule wrote:\n>\n>\n> čt 10. 12. 2020 v 16:48 odesílatel Konstantin Knizhnik \n> <k.knizhnik@postgrespro.ru <mailto:k.knizhnik@postgrespro.ru>> napsal:\n>\n>\n>\n> On 10.12.2020 18:12, Pavel Stehule wrote:\n>>\n>> My idea was a little bit different. Inside postinit initialize\n>> some global variables with info if there are event triggers or\n>> not. And later you can use this variable to start transactions\n>> and  other things.\n>>\n>> There will be two access to pg_event_trigger, but it can\n>> eliminate useless and probably more expensive start_transaction\n>> and end_transaction.\n>>\n>\n>\n> Do you mean some variable in shared memory or GUCs?\n> It was my first idea - to use some flag in shared memory to make\n> it possible fast check that there are not event triggers.\n> But this flag should be sent per database. May be I missed\n> something, but there is no any per-database shared memory data\n> structure in Postgres.\n> Certainly it is possible to organize some hash db->event_info, but\n> it makes this patch several times more complex.\n>\n>\n> My idea was a little bit different - just inside process \n> initialization, checking existence of event triggers, and later when \n> it is necessary to start a transaction for trigger execution. This \n> should to reduce useless empty transaction,\n>\n> I am sure this is a problem on computers with slower CPU s, although I \n> have I7, but because this feature is usually unused, then the \n> performance impact should be minimal every time.\n>\nSorry, may be I missed something. But now I completely confused with \nyour idea.\nRight now processing of login hooks is done in PostgresMain.\nIn the previous mail you have suggested to did it in InitPostgres which \nis invoked from PostgresMain.\nSo what is the difference (except there open transaction in InitPostgres)?\n\nSo what the problem we are trying to solve now?\nAs far as I understand, your concern is about extra overhead during \nbackend startup needed to check if there on-login triggers defined.\nWe are not speaking about trigger execution. We mostly worry about \napplications which are not using triggers at all. But still have to pay \nsome small extra overhead at startup.\nThis overhead seems to be negligible (1% for dummy connection doing just \n\"select 1\"). But taken in account that 99.9999% applications will not \nuse connection triggers,\neven very small overhead seems to be not good.\n\nBut what can we do?\nWe do not want to scan pg_event_trigger table on backend startup. But \nhow else we can skip this check, taken in account that\n1. Such trigger can be registered at any moment of time\n2. Triggers are registered per database, so we can not have just global \nflag,signaling lack of event triggers.\n\nThe only solution I see at this moment is <db,has_event_triggers> hash \nin shared memory.\nBut it seems to be overkill from my point of view.\n\nThis is why I suggested to have disable_login_event_triggers GUC set to \ntrue by default.\n\n\n\n>\n> From my point of view it is better to have separate GUC disabling\n> just client connection events and switch it on by default.\n> So only those who need this events with switch it on, other users\n> will not pay any extra cost for it.\n>\n>\n> It can work, but this design is not user friendly.  The significant \n> bottleneck should be forking new processes, and check of content some \n> usually very small tables should be invisible. So if there is a \n> possible way to implement some feature that can be enabled by default, \n> then we should go this way. It can be pretty unfriendly if somebody \n> writes a logon trigger and it will not work by default without any \n> warning.\nPlease notice that event triggers are disabled by default.\nYou need to call \"alter event trigger xxx enable always\".\nMay be instead of GUCs we should somehow use ALTER mechanism?\nBut I do not understand why it is better and how it will help to solve \nthis problem (elimination of exrta overhead when there are not triggers).\n\n>\n> When I tested last patch I found a problem (I have disabled assertions \n> due performance testing)\n>\n> create role xx login;\n> alter system set disable_event_triggers to on; -- better should be \n> positive form - enable_event_triggers to on, off\n> select pg_reload_conf();\n>\n> psql -U xx\n>\n> Thread 2.1 \"postmaster\" received signal SIGSEGV, Segmentation fault.\n> [Switching to Thread 0x7f2bff438ec0 (LWP 827497)]\n> ResourceOwnerEnlargeCatCacheRefs (owner=0x0) at resowner.c:1025\n> 1025 ResourceArrayEnlarge(&(owner->catrefarr));\n> (gdb) bt\n> #0  ResourceOwnerEnlargeCatCacheRefs (owner=0x0) at resowner.c:1025\n> #1  0x00000000008a70f8 in SearchCatCacheInternal (cache=<optimized \n> out>, nkeys=nkeys@entry=1, v1=v1@entry=13836, v2=v2@entry=0,\n>     v3=v3@entry=0, v4=v4@entry=0) at catcache.c:1273\n> #2  0x00000000008a7575 in SearchCatCache1 (cache=<optimized out>, \n> v1=v1@entry=13836) at catcache.c:1167\n> #3  0x00000000008b7f80 in SearchSysCache1 (cacheId=cacheId@entry=21, \n> key1=key1@entry=13836) at syscache.c:1122\n> #4  0x00000000005939cd in pg_database_ownercheck (db_oid=13836, \n> roleid=16387) at aclchk.c:5114\n> #5  0x0000000000605b42 in EventTriggersDisabled () at event_trigger.c:650\n> #6  EventTriggerOnConnect () at event_trigger.c:839\n> #7  0x00000000007b46d7 in PostgresMain (argc=argc@entry=1, \n> argv=argv@entry=0x7ffdd6256080, dbname=<optimized out>,\n>     username=0xf82508 \"tom\") at postgres.c:4021\n> #8  0x0000000000741afd in BackendRun (port=<optimized out>, \n> port=<optimized out>) at postmaster.c:4490\n> #9  BackendStartup (port=<optimized out>) at postmaster.c:4212\n> #10 ServerLoop () at postmaster.c:1729\n> #11 0x0000000000742881 in PostmasterMain (argc=argc@entry=3, \n> argv=argv@entry=0xf44d00) at postmaster.c:1401\n> #12 0x00000000004f1ff7 in main (argc=3, argv=0xf44d00) at main.c:209\n>\n\n\npg_database_ownercheck can not be called outside transaction.\nI can split replace call of EventTriggersDisabled in \nEventTriggerOnConnect with two separate checks:\ndisable_event_triggers - before start of transaction\nand pg_database_ownercheck(MyDatabaseId, GetUserId()) inside transaction.\n\nBut I wonder if we need to check database ownership in this place at all?\nMay be just allow to alter disable_event_triggers for superusers?\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 10.12.2020 21:09, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\n\nčt 10. 12. 2020 v 16:48\n odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n \n\nOn 10.12.2020 18:12, Pavel Stehule wrote:\n\n\n\n\nMy idea was a little bit different. Inside\n postinit initialize some global variables with\n info if there are event triggers or not. And later\n you can use this variable to start transactions\n and  other things.\n\n\nThere will be two access to pg_event_trigger,\n but it can eliminate useless and probably more\n expensive start_transaction and end_transaction.\n\n\n\n\n\n\n Do you mean some variable in shared memory or GUCs?\n It was my first idea - to use some flag in shared memory\n to make it possible fast check that there are not event\n triggers.\n But this flag should be sent per database. May be I missed\n something, but there is no any per-database shared memory \n data structure in Postgres.\n Certainly it is possible to organize some hash\n db->event_info, but it makes this patch several times\n more complex.\n\n\n\n\nMy idea was a little bit different - just inside process\n initialization, checking existence of event triggers, and\n later when it is necessary to start a transaction for\n trigger execution. This should to reduce useless empty\n transaction, \n\n\n\nI am sure this is a problem on computers with slower CPU\n s, although I have I7, but because this feature is usually\n unused, then the performance impact should be minimal every\n time. \n\n\n\n\n\n\n Sorry, may be I missed something. But now I completely confused with\n your idea.\n Right now processing of login hooks is done in PostgresMain.\n In the previous mail you have suggested to did it in InitPostgres\n which is invoked from PostgresMain.\n So what is the difference (except there open transaction in\n InitPostgres)?\n\n So what the problem we are trying to solve now?\n As far as I understand, your concern is about extra overhead during\n backend startup needed to check if there on-login triggers defined.\n We are not speaking about trigger execution. We mostly worry about\n applications which are not using triggers at all. But still have to\n pay some small extra overhead at startup.\n This overhead seems to be negligible (1% for dummy connection doing\n just \"select 1\"). But taken in account that 99.9999% applications\n will not use connection triggers,\n even very small overhead seems to be not good.\n\n But what can we do?\n We do not want to scan pg_event_trigger table on backend startup.\n But how else we can skip this check, taken in account that \n 1. Such trigger can be registered at any moment of time\n 2. Triggers are registered per database, so we can not have just\n global flag,signaling lack of event triggers.\n\n The only solution I see at this moment is\n <db,has_event_triggers> hash in shared memory.\n But it seems to be overkill from my point of view.\n\n This is why I suggested to have disable_login_event_triggers GUC \n set to true by default.\n\n\n\n\n\n\n \n\n \n From my point of view it is better to have separate GUC\n disabling just client connection events and switch it on\n by default.\n So only those who need this events with switch it on,\n other users will not pay any extra cost for it.\n\n\n\n\nIt can work, but this design is not user friendly.  The\n significant bottleneck should be forking new processes, and\n check of content some usually very small tables should be\n invisible. So if there is a possible way to implement some\n feature that can be enabled by default, then we should go\n this way. It can be pretty unfriendly if somebody writes a\n logon trigger and it will not work by default without any\n warning. \n\n\n\n\n Please notice that event triggers are disabled by default.\n You need to call \"alter event trigger xxx enable always\".\n May be instead of GUCs we should somehow use ALTER mechanism?\n But I do not understand why it is better and how it will help to\n solve this problem (elimination of exrta overhead when there are not\n triggers).\n\n\n\n\n\n\nWhen I tested last patch I found a problem (I have\n disabled assertions due performance testing)\n\n\n\ncreate role xx login;\nalter system set disable_event_triggers to on; -- better\n should be positive form - enable_event_triggers to on, off\nselect pg_reload_conf();\n\n\npsql -U xx\n\n\nThread 2.1 \"postmaster\" received signal SIGSEGV,\n Segmentation fault.\n [Switching to Thread 0x7f2bff438ec0 (LWP 827497)]\n ResourceOwnerEnlargeCatCacheRefs (owner=0x0) at\n resowner.c:1025\n 1025 ResourceArrayEnlarge(&(owner->catrefarr));\n (gdb) bt\n #0  ResourceOwnerEnlargeCatCacheRefs (owner=0x0) at\n resowner.c:1025\n #1  0x00000000008a70f8 in SearchCatCacheInternal\n (cache=<optimized out>, nkeys=nkeys@entry=1,\n v1=v1@entry=13836, v2=v2@entry=0, \n     v3=v3@entry=0, v4=v4@entry=0) at catcache.c:1273\n #2  0x00000000008a7575 in SearchCatCache1\n (cache=<optimized out>, v1=v1@entry=13836) at\n catcache.c:1167\n #3  0x00000000008b7f80 in SearchSysCache1\n (cacheId=cacheId@entry=21, key1=key1@entry=13836) at\n syscache.c:1122\n #4  0x00000000005939cd in pg_database_ownercheck\n (db_oid=13836, roleid=16387) at aclchk.c:5114\n #5  0x0000000000605b42 in EventTriggersDisabled () at\n event_trigger.c:650\n #6  EventTriggerOnConnect () at event_trigger.c:839\n #7  0x00000000007b46d7 in PostgresMain (argc=argc@entry=1,\n argv=argv@entry=0x7ffdd6256080, dbname=<optimized\n out>, \n     username=0xf82508 \"tom\") at postgres.c:4021\n #8  0x0000000000741afd in BackendRun (port=<optimized\n out>, port=<optimized out>) at postmaster.c:4490\n #9  BackendStartup (port=<optimized out>) at\n postmaster.c:4212\n #10 ServerLoop () at postmaster.c:1729\n #11 0x0000000000742881 in PostmasterMain (argc=argc@entry=3,\n argv=argv@entry=0xf44d00) at postmaster.c:1401\n #12 0x00000000004f1ff7 in main (argc=3, argv=0xf44d00) at\n main.c:209\n\n\n\n\n\n\n\n\n pg_database_ownercheck can not be called outside transaction.\n I can split replace call of EventTriggersDisabled in\n EventTriggerOnConnect with two separate checks: \n disable_event_triggers - before start of transaction \n and pg_database_ownercheck(MyDatabaseId, GetUserId()) inside\n transaction.\n\n But I wonder if we need to check database ownership in this place at\n all?\n May be just allow to alter disable_event_triggers for superusers?\n\n\n \n\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 11 Dec 2020 17:19:13 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 09.12.2020 15:24, Pavel Stehule wrote:\n>\n>\n> st 9. 12. 2020 v 13:17 odesílatel Greg Nancarrow <gregn4422@gmail.com \n> <mailto:gregn4422@gmail.com>> napsal:\n>\n> On Tue, Dec 8, 2020 at 3:26 PM Pavel Stehule\n> <pavel.stehule@gmail.com <mailto:pavel.stehule@gmail.com>> wrote:\n> >\n> >\n> > There are two maybe generic questions?\n> >\n> > 1. Maybe we can introduce more generic GUC for all event\n> triggers like disable_event_triggers? This GUC can be checked only\n> by the database owner or super user. It can be an alternative\n> ALTER TABLE DISABLE TRIGGER ALL. It can be protection against\n> necessity to restart to single mode to repair the event trigger. I\n> think so more generic solution is better than special\n> disable_client_connection_trigger GUC.\n> >\n> > 2. I have no objection against client_connection. It is probably\n> better for the mentioned purpose - possibility to block connection\n> to database. Can be interesting, and I am not sure how much work\n> it is to introduce the second event - session_start. This event\n> should be started after connecting - so the exception there\n> doesn't block connect, and should be started also after the new\n> statement \"DISCARD SESSION\", that will be started automatically\n> after DISCARD ALL.  This feature should not be implemented in\n> first step, but it can be a plan for support pooled connections\n> >\n>\n>\n> PGC_SU_BACKEND is too strong, there should be PGC_BACKEND if this \n> option can be used by database owner\n>\n> Pavel\n>\n>\n> I've created a separate patch to address question (1), rather than\n> include it in the main patch, which I've adjusted accordingly. I'll\n> leave question (2) until another time, as you suggest.\n> See the attached patches.\n>\n> Regards,\n> Greg Nancarrow\n> Fujitsu Australia\n>\n\nIt seems to me that current implementation of EventTriggersDisabled:\n\n\n  /*\n  * Indicates whether all event triggers are currently disabled\n  * for the current user.\n  * Event triggers are disabled when configuration parameter\n  * \"disable_event_triggers\" is true, and the current user\n  * is the database owner or has superuser privileges.\n  */\nstatic inline bool\nEventTriggersDisabled(void)\n{\n     return (disable_event_triggers && \npg_database_ownercheck(MyDatabaseId, GetUserId()));\n}\n\n\nis not correct. It makes it not possible to superuser to disable \ntriggers for all users.\nAlso GUCs are not associated with any database. So I do not understand \nwhy  this check of database ownership is relevant at all?\n\nWhat kind of protection violation we want to prevent?\n\nIt seems to be obvious that normal user should not be able to prevent \ntrigger execution because this triggers may be used to enforce some \nsecurity policies.\nIf trigger was created by user itself, then it can drop or disable it \nusing ALTER statement. GUC is not needed for it.\n\nSo I think that EventTriggersDisabled function is not needed and can be \nreplaced just with disable_event_triggers GUC check.\nAnd this option should be defined with PGC_SU_BACKEND\n\n\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 09.12.2020 15:24, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\n\nst 9. 12. 2020 v 13:17\n odesílatel Greg Nancarrow <gregn4422@gmail.com>\n napsal:\n\nOn Tue, Dec 8, 2020 at\n 3:26 PM Pavel Stehule <pavel.stehule@gmail.com>\n wrote:\n >\n >\n > There are two maybe generic questions?\n >\n > 1. Maybe we can introduce more generic GUC for all\n event triggers like disable_event_triggers? This GUC can be\n checked only by the database owner or super user. It can be\n an alternative ALTER TABLE DISABLE TRIGGER ALL. It can be\n protection against necessity to restart to single mode to\n repair the event trigger. I think so more generic solution\n is better than special disable_client_connection_trigger\n GUC.\n >\n > 2. I have no objection against client_connection. It is\n probably better for the mentioned purpose - possibility to\n block connection to database. Can be interesting, and I am\n not sure how much work it is to introduce the second event -\n session_start. This event should be started after connecting\n - so the exception there doesn't block connect, and should\n be started also after the new statement \"DISCARD SESSION\",\n that will be started automatically after DISCARD ALL.  This\n feature should not be implemented in first step, but it can\n be a plan for support pooled connections\n >\n\n\n\nPGC_SU_BACKEND is too strong, there should be PGC_BACKEND\n if this option can be used by database owner\n\n\nPavel\n\n\n\n\n\n I've created a separate patch to address question (1),\n rather than\n include it in the main patch, which I've adjusted\n accordingly. I'll\n leave question (2) until another time, as you suggest.\n See the attached patches.\n\n Regards,\n Greg Nancarrow\n Fujitsu Australia\n\n\n\n\n\n It seems to me that current implementation of EventTriggersDisabled:\n\n\n  /*\n  * Indicates whether all event triggers are currently disabled\n  * for the current user.\n  * Event triggers are disabled when configuration parameter\n  * \"disable_event_triggers\" is true, and the current user\n  * is the database owner or has superuser privileges.\n  */\n static inline bool\n EventTriggersDisabled(void)\n {\n     return (disable_event_triggers &&\n pg_database_ownercheck(MyDatabaseId, GetUserId()));\n }\n\n\n is not correct. It makes it not possible to superuser to disable\n triggers for all users.\n Also GUCs are not associated with any database. So I do not\n understand why  this check of database ownership is relevant at all?\n\n What kind of protection violation we want to prevent?\n\n It seems to be obvious that normal user should not be able to\n prevent trigger execution because this triggers may be used to\n enforce some security policies.\n If trigger was created by user itself, then it can drop or disable\n it using ALTER statement. GUC is not needed for it.\n\n So I think that EventTriggersDisabled function is not needed and can\n be replaced just with disable_event_triggers GUC check.\n And this option should be defined with PGC_SU_BACKEND\n\n\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 11 Dec 2020 18:07:16 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "pá 11. 12. 2020 v 16:07 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 09.12.2020 15:24, Pavel Stehule wrote:\n>\n>\n>\n> st 9. 12. 2020 v 13:17 odesílatel Greg Nancarrow <gregn4422@gmail.com>\n> napsal:\n>\n>> On Tue, Dec 8, 2020 at 3:26 PM Pavel Stehule <pavel.stehule@gmail.com>\n>> wrote:\n>> >\n>> >\n>> > There are two maybe generic questions?\n>> >\n>> > 1. Maybe we can introduce more generic GUC for all event triggers like\n>> disable_event_triggers? This GUC can be checked only by the database owner\n>> or super user. It can be an alternative ALTER TABLE DISABLE TRIGGER ALL. It\n>> can be protection against necessity to restart to single mode to repair the\n>> event trigger. I think so more generic solution is better than special\n>> disable_client_connection_trigger GUC.\n>> >\n>> > 2. I have no objection against client_connection. It is probably better\n>> for the mentioned purpose - possibility to block connection to database.\n>> Can be interesting, and I am not sure how much work it is to introduce the\n>> second event - session_start. This event should be started after connecting\n>> - so the exception there doesn't block connect, and should be started also\n>> after the new statement \"DISCARD SESSION\", that will be started\n>> automatically after DISCARD ALL. This feature should not be implemented in\n>> first step, but it can be a plan for support pooled connections\n>> >\n>>\n>\n> PGC_SU_BACKEND is too strong, there should be PGC_BACKEND if this option\n> can be used by database owner\n>\n> Pavel\n>\n>\n>> I've created a separate patch to address question (1), rather than\n>> include it in the main patch, which I've adjusted accordingly. I'll\n>> leave question (2) until another time, as you suggest.\n>> See the attached patches.\n>>\n>> Regards,\n>> Greg Nancarrow\n>> Fujitsu Australia\n>>\n>\n> It seems to me that current implementation of EventTriggersDisabled:\n>\n>\n> /*\n> * Indicates whether all event triggers are currently disabled\n> * for the current user.\n> * Event triggers are disabled when configuration parameter\n> * \"disable_event_triggers\" is true, and the current user\n> * is the database owner or has superuser privileges.\n> */\n> static inline bool\n> EventTriggersDisabled(void)\n> {\n> return (disable_event_triggers && pg_database_ownercheck(MyDatabaseId,\n> GetUserId()));\n> }\n>\n>\n> is not correct. It makes it not possible to superuser to disable triggers\n> for all users.\n>\n\npg_database_ownercheck returns true for superuser always.\n\nAlso GUCs are not associated with any database. So I do not understand why\n> this check of database ownership is relevant at all?\n>\n> What kind of protection violation we want to prevent?\n>\n> It seems to be obvious that normal user should not be able to prevent\n> trigger execution because this triggers may be used to enforce some\n> security policies.\n> If trigger was created by user itself, then it can drop or disable it\n> using ALTER statement. GUC is not needed for it.\n>\n\nwhen you cannot connect to the database, then you cannot do ALTER. In DBaaS\nenvironments lot of users has not superuser rights.\n\n\n\n> So I think that EventTriggersDisabled function is not needed and can be\n> replaced just with disable_event_triggers GUC check.\n> And this option should be defined with PGC_SU_BACKEND\n>\n>\n>\n>\n> --\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>\n\npá 11. 12. 2020 v 16:07 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n\n\nOn 09.12.2020 15:24, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\nst 9. 12. 2020 v 13:17\n odesílatel Greg Nancarrow <gregn4422@gmail.com>\n napsal:\n\nOn Tue, Dec 8, 2020 at\n 3:26 PM Pavel Stehule <pavel.stehule@gmail.com>\n wrote:\n >\n >\n > There are two maybe generic questions?\n >\n > 1. Maybe we can introduce more generic GUC for all\n event triggers like disable_event_triggers? This GUC can be\n checked only by the database owner or super user. It can be\n an alternative ALTER TABLE DISABLE TRIGGER ALL. It can be\n protection against necessity to restart to single mode to\n repair the event trigger. I think so more generic solution\n is better than special disable_client_connection_trigger\n GUC.\n >\n > 2. I have no objection against client_connection. It is\n probably better for the mentioned purpose - possibility to\n block connection to database. Can be interesting, and I am\n not sure how much work it is to introduce the second event -\n session_start. This event should be started after connecting\n - so the exception there doesn't block connect, and should\n be started also after the new statement \"DISCARD SESSION\",\n that will be started automatically after DISCARD ALL.  This\n feature should not be implemented in first step, but it can\n be a plan for support pooled connections\n >\n\n\n\nPGC_SU_BACKEND is too strong, there should be PGC_BACKEND\n if this option can be used by database owner\n\n\nPavel\n\n\n\n\n\n I've created a separate patch to address question (1),\n rather than\n include it in the main patch, which I've adjusted\n accordingly. I'll\n leave question (2) until another time, as you suggest.\n See the attached patches.\n\n Regards,\n Greg Nancarrow\n Fujitsu Australia\n\n\n\n\n\n It seems to me that current implementation of EventTriggersDisabled:\n\n\n  /*\n  * Indicates whether all event triggers are currently disabled\n  * for the current user.\n  * Event triggers are disabled when configuration parameter\n  * \"disable_event_triggers\" is true, and the current user\n  * is the database owner or has superuser privileges.\n  */\n static inline bool\n EventTriggersDisabled(void)\n {\n     return (disable_event_triggers &&\n pg_database_ownercheck(MyDatabaseId, GetUserId()));\n }\n\n\n is not correct. It makes it not possible to superuser to disable\n triggers for all users.pg_database_ownercheck returns true for superuser always. \n Also GUCs are not associated with any database. So I do not\n understand why  this check of database ownership is relevant at all?\n\n What kind of protection violation we want to prevent?\n\n It seems to be obvious that normal user should not be able to\n prevent trigger execution because this triggers may be used to\n enforce some security policies.\n If trigger was created by user itself, then it can drop or disable\n it using ALTER statement. GUC is not needed for it.when you cannot connect to the database, then you cannot do ALTER. In DBaaS environments lot of users has not superuser rights. \n\n So I think that EventTriggersDisabled function is not needed and can\n be replaced just with disable_event_triggers GUC check.\n And this option should be defined with PGC_SU_BACKEND\n\n\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 11 Dec 2020 16:40:19 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 11.12.2020 18:40, Pavel Stehule wrote:\n>\n> is not correct. It makes it not possible to superuser to disable\n> triggers for all users.\n>\n>\n> pg_database_ownercheck returns true for superuser always.\n\nSorry, but I consider different case: when normal user is connected to \nthe database.\nIn this case pg_database_ownercheck returns false and trigger is not \ndisabled, isn't it?\n\n>\n> Also GUCs are not associated with any database. So I do not\n> understand why  this check of database ownership is relevant at all?\n>\n> What kind of protection violation we want to prevent?\n>\n> It seems to be obvious that normal user should not be able to\n> prevent trigger execution because this triggers may be used to\n> enforce some security policies.\n> If trigger was created by user itself, then it can drop or disable\n> it using ALTER statement. GUC is not needed for it.\n>\n>\n> when you cannot connect to the database, then you cannot do ALTER. In \n> DBaaS environments lot of users has not superuser rights.\n\n\nBut only superusers can set login triggers, right?\nSo only superuser can make a mistake in this trigger. But he have enough \nrights to recover this error. Normal users are not able to define on \nconnection triggers and\nshould not have rights to disable them.\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n\n\n\n\n\n\nOn 11.12.2020 18:40, Pavel Stehule\n wrote:\n\n\n\n\n\n\n is not correct. It makes it not\n possible to superuser to disable triggers for all users.\n\n\n\n\npg_database_ownercheck returns true for superuser always.\n\n\n\n\n Sorry, but I consider different case: when normal user is connected\n to the database.\n In this case pg_database_ownercheck returns false and trigger is not\n disabled, isn't it?\n\n\n\n\n \n\n\n Also GUCs are not associated with\n any database. So I do not understand why  this check of\n database ownership is relevant at all?\n\n What kind of protection violation we want to prevent?\n\n It seems to be obvious that normal user should not be able\n to prevent trigger execution because this triggers may be\n used to enforce some security policies.\n If trigger was created by user itself, then it can drop or\n disable it using ALTER statement. GUC is not needed for\n it.\n\n\n\n\nwhen you cannot connect to the database, then you cannot\n do ALTER. In DBaaS environments lot of users has not\n superuser rights.\n\n\n\n\n\n\n But only superusers can set login triggers, right? \n So only superuser can make a mistake in this trigger. But he have\n enough rights to recover this error. Normal users are not able to\n define on connection triggers and \n should not have rights to disable them.\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 11 Dec 2020 19:05:26 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "pá 11. 12. 2020 v 17:05 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 11.12.2020 18:40, Pavel Stehule wrote:\n>\n>\n> is not correct. It makes it not possible to superuser to disable triggers\n>> for all users.\n>>\n>\n> pg_database_ownercheck returns true for superuser always.\n>\n>\n> Sorry, but I consider different case: when normal user is connected to the\n> database.\n> In this case pg_database_ownercheck returns false and trigger is not\n> disabled, isn't it?\n>\n\nMy idea was to reduce necessary rights to database owners. But you have a\ntrue, so only superuser can create event trigger, so this feature cannot be\nused in DBaaS environments, and then my original idea was wrong.\n\n\n>\n> Also GUCs are not associated with any database. So I do not understand\n>> why this check of database ownership is relevant at all?\n>>\n>> What kind of protection violation we want to prevent?\n>>\n>> It seems to be obvious that normal user should not be able to prevent\n>> trigger execution because this triggers may be used to enforce some\n>> security policies.\n>> If trigger was created by user itself, then it can drop or disable it\n>> using ALTER statement. GUC is not needed for it.\n>>\n>\n> when you cannot connect to the database, then you cannot do ALTER. In\n> DBaaS environments lot of users has not superuser rights.\n>\n>\n>\n> But only superusers can set login triggers, right?\n> So only superuser can make a mistake in this trigger. But he have enough\n> rights to recover this error. Normal users are not able to define on\n> connection triggers and\n> should not have rights to disable them.\n>\n\nyes, it is true\n\nPavel\n\n\n> --\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>\n\npá 11. 12. 2020 v 17:05 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n\n\nOn 11.12.2020 18:40, Pavel Stehule\n wrote:\n\n\n\n\n\n is not correct. It makes it not\n possible to superuser to disable triggers for all users.\n\n\n\n\npg_database_ownercheck returns true for superuser always.\n\n\n\n\n Sorry, but I consider different case: when normal user is connected\n to the database.\n In this case pg_database_ownercheck returns false and trigger is not\n disabled, isn't it?My idea was to reduce necessary rights to database owners.  But you have a true, so only superuser can create event trigger, so this feature cannot be used in DBaaS environments, and then my original idea was wrong.\n\n\n\n\n \n\n\n Also GUCs are not associated with\n any database. So I do not understand why  this check of\n database ownership is relevant at all?\n\n What kind of protection violation we want to prevent?\n\n It seems to be obvious that normal user should not be able\n to prevent trigger execution because this triggers may be\n used to enforce some security policies.\n If trigger was created by user itself, then it can drop or\n disable it using ALTER statement. GUC is not needed for\n it.\n\n\n\n\nwhen you cannot connect to the database, then you cannot\n do ALTER. In DBaaS environments lot of users has not\n superuser rights.\n\n\n\n\n\n\n But only superusers can set login triggers, right? \n So only superuser can make a mistake in this trigger. But he have\n enough rights to recover this error. Normal users are not able to\n define on connection triggers and \n should not have rights to disable them.yes, it is truePavel\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 11 Dec 2020 17:27:27 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 11.12.2020 19:27, Pavel Stehule wrote:\n>\n>\n> pá 11. 12. 2020 v 17:05 odesílatel Konstantin Knizhnik \n> <k.knizhnik@postgrespro.ru <mailto:k.knizhnik@postgrespro.ru>> napsal:\n>\n>\n>\n> On 11.12.2020 18:40, Pavel Stehule wrote:\n>>\n>> is not correct. It makes it not possible to superuser to\n>> disable triggers for all users.\n>>\n>>\n>> pg_database_ownercheck returns true for superuser always.\n>\n> Sorry, but I consider different case: when normal user is\n> connected to the database.\n> In this case pg_database_ownercheck returns false and trigger is\n> not disabled, isn't it?\n>\n>\n> My idea was to reduce necessary rights to database owners.  But you \n> have a true, so only superuser can create event trigger, so this \n> feature cannot be used in DBaaS environments, and then my original \n> idea was wrong.\n>\n>\n>>\n>> Also GUCs are not associated with any database. So I do not\n>> understand why  this check of database ownership is relevant\n>> at all?\n>>\n>> What kind of protection violation we want to prevent?\n>>\n>> It seems to be obvious that normal user should not be able to\n>> prevent trigger execution because this triggers may be used\n>> to enforce some security policies.\n>> If trigger was created by user itself, then it can drop or\n>> disable it using ALTER statement. GUC is not needed for it.\n>>\n>>\n>> when you cannot connect to the database, then you cannot do\n>> ALTER. In DBaaS environments lot of users has not superuser rights.\n>\n>\n> But only superusers can set login triggers, right?\n> So only superuser can make a mistake in this trigger. But he have\n> enough rights to recover this error. Normal users are not able to\n> define on connection triggers and\n> should not have rights to disable them.\n>\n>\n> yes, it is true\n>\n> Pavel\n>\n>\n> -- \n> Konstantin Knizhnik\n> Postgres Professional:http://www.postgrespro.com\n> The Russian Postgres Company\n>\n\nSo what's next?\nI see three options:\n\n1. Do not introduce GUC for disabling all event triggers (especially \ntaken in account that them are  disabled by default).\nReturn back to the patch \non_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch with \n\"disable_client_connection_trigger\"\nand make it true by default (to eliminate any overhead for users which \nare not using on logintriggers).\n\n2. Have two GUCS: \"disable_client_connection_trigger\" and \n\"disable_event_triggers\".\n\n3. Implement some mechanism for caching presence of event triggers in \nshared memory.\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 11.12.2020 19:27, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\n\npá 11. 12. 2020 v 17:05\n odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n \n\nOn 11.12.2020 18:40, Pavel Stehule wrote:\n\n\n\n\n\n is not correct. It makes\n it not possible to superuser to disable triggers\n for all users.\n\n\n\n\npg_database_ownercheck returns true for\n superuser always.\n\n\n\n\n Sorry, but I consider different case: when normal user is\n connected to the database.\n In this case pg_database_ownercheck returns false and\n trigger is not disabled, isn't it?\n\n\n\n\nMy idea was to reduce necessary rights to database\n owners.  But you have a true, so only superuser can create\n event trigger, so this feature cannot be used in DBaaS\n environments, and then my original idea was wrong.\n\n\n\n \n\n\n\n \n\n\n Also GUCs are not\n associated with any database. So I do not\n understand why  this check of database ownership\n is relevant at all?\n\n What kind of protection violation we want to\n prevent?\n\n It seems to be obvious that normal user should\n not be able to prevent trigger execution because\n this triggers may be used to enforce some\n security policies.\n If trigger was created by user itself, then it\n can drop or disable it using ALTER statement.\n GUC is not needed for it.\n\n\n\n\nwhen you cannot connect to the database, then\n you cannot do ALTER. In DBaaS environments lot of\n users has not superuser rights.\n\n\n\n\n\n\n But only superusers can set login triggers, right? \n So only superuser can make a mistake in this trigger. But\n he have enough rights to recover this error. Normal users\n are not able to define on connection triggers and \n should not have rights to disable them.\n\n\n\n\nyes, it is true\n\n\nPavel\n\n\n\n \n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company \n\n\n\n\n\n\n So what's next?\n I see three options:\n\n 1. Do not introduce GUC for disabling all event triggers (especially\n taken in account that them are  disabled by default).\n Return back to the patch\n on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch with\n \"disable_client_connection_trigger\"\n and make it true by default (to eliminate any overhead for users\n which are not using on logintriggers).\n\n 2. Have two GUCS: \"disable_client_connection_trigger\" and\n \"disable_event_triggers\".\n\n 3. Implement some mechanism for caching presence of event triggers\n in shared memory.\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Tue, 15 Dec 2020 16:12:40 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "út 15. 12. 2020 v 14:12 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 11.12.2020 19:27, Pavel Stehule wrote:\n>\n>\n>\n> pá 11. 12. 2020 v 17:05 odesílatel Konstantin Knizhnik <\n> k.knizhnik@postgrespro.ru> napsal:\n>\n>>\n>>\n>> On 11.12.2020 18:40, Pavel Stehule wrote:\n>>\n>>\n>> is not correct. It makes it not possible to superuser to disable triggers\n>>> for all users.\n>>>\n>>\n>> pg_database_ownercheck returns true for superuser always.\n>>\n>>\n>> Sorry, but I consider different case: when normal user is connected to\n>> the database.\n>> In this case pg_database_ownercheck returns false and trigger is not\n>> disabled, isn't it?\n>>\n>\n> My idea was to reduce necessary rights to database owners. But you have a\n> true, so only superuser can create event trigger, so this feature cannot be\n> used in DBaaS environments, and then my original idea was wrong.\n>\n>\n>>\n>> Also GUCs are not associated with any database. So I do not understand\n>>> why this check of database ownership is relevant at all?\n>>>\n>>> What kind of protection violation we want to prevent?\n>>>\n>>> It seems to be obvious that normal user should not be able to prevent\n>>> trigger execution because this triggers may be used to enforce some\n>>> security policies.\n>>> If trigger was created by user itself, then it can drop or disable it\n>>> using ALTER statement. GUC is not needed for it.\n>>>\n>>\n>> when you cannot connect to the database, then you cannot do ALTER. In\n>> DBaaS environments lot of users has not superuser rights.\n>>\n>>\n>>\n>> But only superusers can set login triggers, right?\n>> So only superuser can make a mistake in this trigger. But he have enough\n>> rights to recover this error. Normal users are not able to define on\n>> connection triggers and\n>> should not have rights to disable them.\n>>\n>\n> yes, it is true\n>\n> Pavel\n>\n>\n>> --\n>> Konstantin Knizhnik\n>> Postgres Professional: http://www.postgrespro.com\n>> The Russian Postgres Company\n>>\n>>\n> So what's next?\n> I see three options:\n>\n> 1. Do not introduce GUC for disabling all event triggers (especially taken\n> in account that them are disabled by default).\n> Return back to the patch\n> on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch with\n> \"disable_client_connection_trigger\"\n> and make it true by default (to eliminate any overhead for users which are\n> not using on logintriggers).\n>\n> 2. Have two GUCS: \"disable_client_connection_trigger\" and\n> \"disable_event_triggers\".\n>\n> 3. Implement some mechanism for caching presence of event triggers in\n> shared memory.\n>\n\n@3 is the best design (the things should work well by default), @2 is a\nlittle bit chaotic and @1 looks like a workaround.\n\nRegards\n\nPavel\n\n\n>\n> --\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>\n\nút 15. 12. 2020 v 14:12 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n\n\nOn 11.12.2020 19:27, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\npá 11. 12. 2020 v 17:05\n odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n \n\nOn 11.12.2020 18:40, Pavel Stehule wrote:\n\n\n\n\n\n is not correct. It makes\n it not possible to superuser to disable triggers\n for all users.\n\n\n\n\npg_database_ownercheck returns true for\n superuser always.\n\n\n\n\n Sorry, but I consider different case: when normal user is\n connected to the database.\n In this case pg_database_ownercheck returns false and\n trigger is not disabled, isn't it?\n\n\n\n\nMy idea was to reduce necessary rights to database\n owners.  But you have a true, so only superuser can create\n event trigger, so this feature cannot be used in DBaaS\n environments, and then my original idea was wrong.\n\n\n\n \n\n\n\n \n\n\n Also GUCs are not\n associated with any database. So I do not\n understand why  this check of database ownership\n is relevant at all?\n\n What kind of protection violation we want to\n prevent?\n\n It seems to be obvious that normal user should\n not be able to prevent trigger execution because\n this triggers may be used to enforce some\n security policies.\n If trigger was created by user itself, then it\n can drop or disable it using ALTER statement.\n GUC is not needed for it.\n\n\n\n\nwhen you cannot connect to the database, then\n you cannot do ALTER. In DBaaS environments lot of\n users has not superuser rights.\n\n\n\n\n\n\n But only superusers can set login triggers, right? \n So only superuser can make a mistake in this trigger. But\n he have enough rights to recover this error. Normal users\n are not able to define on connection triggers and \n should not have rights to disable them.\n\n\n\n\nyes, it is true\n\n\nPavel\n\n\n\n \n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company \n\n\n\n\n\n\n So what's next?\n I see three options:\n\n 1. Do not introduce GUC for disabling all event triggers (especially\n taken in account that them are  disabled by default).\n Return back to the patch\n on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch with\n \"disable_client_connection_trigger\"\n and make it true by default (to eliminate any overhead for users\n which are not using on logintriggers).\n\n 2. Have two GUCS: \"disable_client_connection_trigger\" and\n \"disable_event_triggers\".\n\n 3. Implement some mechanism for caching presence of event triggers\n in shared memory.@3 is the best design (the things should work well by default), @2 is a little bit chaotic and @1 looks like a workaround.RegardsPavel\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Tue, 15 Dec 2020 14:18:43 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 15.12.2020 16:18, Pavel Stehule wrote:\n>\n>\n> út 15. 12. 2020 v 14:12 odesílatel Konstantin Knizhnik \n> <k.knizhnik@postgrespro.ru <mailto:k.knizhnik@postgrespro.ru>> napsal:\n>\n>\n>\n> On 11.12.2020 19:27, Pavel Stehule wrote:\n>>\n>>\n>> pá 11. 12. 2020 v 17:05 odesílatel Konstantin Knizhnik\n>> <k.knizhnik@postgrespro.ru <mailto:k.knizhnik@postgrespro.ru>>\n>> napsal:\n>>\n>>\n>>\n>> On 11.12.2020 18:40, Pavel Stehule wrote:\n>>>\n>>> is not correct. It makes it not possible to superuser to\n>>> disable triggers for all users.\n>>>\n>>>\n>>> pg_database_ownercheck returns true for superuser always.\n>>\n>> Sorry, but I consider different case: when normal user is\n>> connected to the database.\n>> In this case pg_database_ownercheck returns false and trigger\n>> is not disabled, isn't it?\n>>\n>>\n>> My idea was to reduce necessary rights to database owners.  But\n>> you have a true, so only superuser can create event trigger, so\n>> this feature cannot be used in DBaaS environments, and then my\n>> original idea was wrong.\n>>\n>>\n>>>\n>>> Also GUCs are not associated with any database. So I do\n>>> not understand why  this check of database ownership is\n>>> relevant at all?\n>>>\n>>> What kind of protection violation we want to prevent?\n>>>\n>>> It seems to be obvious that normal user should not be\n>>> able to prevent trigger execution because this triggers\n>>> may be used to enforce some security policies.\n>>> If trigger was created by user itself, then it can drop\n>>> or disable it using ALTER statement. GUC is not needed\n>>> for it.\n>>>\n>>>\n>>> when you cannot connect to the database, then you cannot do\n>>> ALTER. In DBaaS environments lot of users has not superuser\n>>> rights.\n>>\n>>\n>> But only superusers can set login triggers, right?\n>> So only superuser can make a mistake in this trigger. But he\n>> have enough rights to recover this error. Normal users are\n>> not able to define on connection triggers and\n>> should not have rights to disable them.\n>>\n>>\n>> yes, it is true\n>>\n>> Pavel\n>>\n>>\n>> -- \n>> Konstantin Knizhnik\n>> Postgres Professional:http://www.postgrespro.com\n>> The Russian Postgres Company\n>>\n>\n> So what's next?\n> I see three options:\n>\n> 1. Do not introduce GUC for disabling all event triggers\n> (especially taken in account that them are  disabled by default).\n> Return back to the patch\n> on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch with\n> \"disable_client_connection_trigger\"\n> and make it true by default (to eliminate any overhead for users\n> which are not using on logintriggers).\n>\n> 2. Have two GUCS: \"disable_client_connection_trigger\" and\n> \"disable_event_triggers\".\n>\n> 3. Implement some mechanism for caching presence of event triggers\n> in shared memory.\n>\n>\n> @3 is the best design (the things should work well by default), @2 is \n> a little bit chaotic and @1 looks like a workaround.\n>\n\nPlease notice that we still need GUC to disable on-login triggers: to \nmake it possible for superuser who did mistake and defined incorrect \non-login trigger to\nlogin to the system.\nDo we need GUC to disable all other event triggers? May be I am wrong, \nbut I do not see much need in such GUC: error in any of such event \ntriggers is non fatal\nand can be easily reverted.\nSo the only question is whether \"disable_client_connection_trigger\" \nshould be true by default or not...\n\nI agree with you that @2 is a little bit chaotic and @1 looks like a \nworkaround.\nBut from my point of view @3 is not the best solution but overkill: \nmaintaining yet another shared hash just to save few milliseconds on \nlogin seems to be too high price.\nActually there are many things which are loaded by new backend from the \ndatabase on start: for example - catalog.\nThis is why launch of new backend is an expensive operation.\nCertainly if we execute \"select 1\", then system catalog is not needed...\nBut does anybody start new backend just to execute \"select 1\" and exit?\n\n\n\n\n\n\n> Regards\n>\n> Pavel\n>\n>\n>\n> -- \n> Konstantin Knizhnik\n> Postgres Professional:http://www.postgrespro.com\n> The Russian Postgres Company\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 15.12.2020 16:18, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\n\nút 15. 12. 2020 v 14:12\n odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n \n\nOn 11.12.2020 19:27, Pavel Stehule wrote:\n\n\n\n\n\n\n\npá 11. 12. 2020\n v 17:05 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n \n\nOn 11.12.2020 18:40, Pavel Stehule wrote:\n\n\n\n\n\n is not correct.\n It makes it not possible to superuser\n to disable triggers for all users.\n\n\n\n\npg_database_ownercheck returns true\n for superuser always.\n\n\n\n\n Sorry, but I consider different case: when\n normal user is connected to the database.\n In this case pg_database_ownercheck returns\n false and trigger is not disabled, isn't it?\n\n\n\n\nMy idea was to reduce necessary rights to\n database owners.  But you have a true, so only\n superuser can create event trigger, so this\n feature cannot be used in DBaaS environments, and\n then my original idea was wrong.\n\n\n\n \n\n\n\n \n\n\n Also GUCs are\n not associated with any database. So I\n do not understand why  this check of\n database ownership is relevant at all?\n\n What kind of protection violation we\n want to prevent?\n\n It seems to be obvious that normal\n user should not be able to prevent\n trigger execution because this\n triggers may be used to enforce some\n security policies.\n If trigger was created by user itself,\n then it can drop or disable it using\n ALTER statement. GUC is not needed for\n it.\n\n\n\n\nwhen you cannot connect to the\n database, then you cannot do ALTER. In\n DBaaS environments lot of users has not\n superuser rights.\n\n\n\n\n\n\n But only superusers can set login triggers,\n right? \n So only superuser can make a mistake in this\n trigger. But he have enough rights to recover\n this error. Normal users are not able to define\n on connection triggers and \n should not have rights to disable them.\n\n\n\n\nyes, it is true\n\n\nPavel\n\n\n\n \n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company \n\n\n\n\n\n\n So what's next?\n I see three options:\n\n 1. Do not introduce GUC for disabling all event triggers\n (especially taken in account that them are  disabled by\n default).\n Return back to the patch\n on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch with\n \"disable_client_connection_trigger\"\n and make it true by default (to eliminate any overhead for\n users which are not using on logintriggers).\n\n 2. Have two GUCS: \"disable_client_connection_trigger\" and\n \"disable_event_triggers\".\n\n 3. Implement some mechanism for caching presence of event\n triggers in shared memory.\n\n\n\n\n@3 is the best design (the things should work well by\n default), @2 is a little bit chaotic and @1 looks like a\n workaround.\n\n\n\n\n\n\n Please notice that we still need GUC to disable on-login triggers:\n to make it possible for superuser who did mistake and defined\n incorrect on-login trigger to\n login to the system.\n Do we need GUC to disable all other event triggers? May be I am\n wrong, but I do not see much need in such GUC: error in any of such\n event triggers is non fatal\n and can be easily reverted.\n So the only question is whether \"disable_client_connection_trigger\"\n should be true by default or not...\n\n I agree with you that @2 is a little bit chaotic and @1 looks like a\n workaround.\n But from my point of view @3 is not the best solution but overkill:\n maintaining yet another shared hash just to save few milliseconds on\n login seems to be too high price.\n Actually there are many things which are loaded by new backend from\n the database on start: for example - catalog. \n This is why launch of new backend is an expensive operation. \n Certainly if we execute \"select 1\", then system catalog is not\n needed...\n But does anybody start new backend just to execute \"select 1\" and\n exit?\n\n\n\n\n\n\n\n\n\nRegards\n\n\nPavel\n\n\n\n\n \n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company \n\n\n\n\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Tue, 15 Dec 2020 17:06:30 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "út 15. 12. 2020 v 15:06 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 15.12.2020 16:18, Pavel Stehule wrote:\n>\n>\n>\n> út 15. 12. 2020 v 14:12 odesílatel Konstantin Knizhnik <\n> k.knizhnik@postgrespro.ru> napsal:\n>\n>>\n>>\n>> On 11.12.2020 19:27, Pavel Stehule wrote:\n>>\n>>\n>>\n>> pá 11. 12. 2020 v 17:05 odesílatel Konstantin Knizhnik <\n>> k.knizhnik@postgrespro.ru> napsal:\n>>\n>>>\n>>>\n>>> On 11.12.2020 18:40, Pavel Stehule wrote:\n>>>\n>>>\n>>> is not correct. It makes it not possible to superuser to disable\n>>>> triggers for all users.\n>>>>\n>>>\n>>> pg_database_ownercheck returns true for superuser always.\n>>>\n>>>\n>>> Sorry, but I consider different case: when normal user is connected to\n>>> the database.\n>>> In this case pg_database_ownercheck returns false and trigger is not\n>>> disabled, isn't it?\n>>>\n>>\n>> My idea was to reduce necessary rights to database owners. But you have\n>> a true, so only superuser can create event trigger, so this feature cannot\n>> be used in DBaaS environments, and then my original idea was wrong.\n>>\n>>\n>>>\n>>> Also GUCs are not associated with any database. So I do not understand\n>>>> why this check of database ownership is relevant at all?\n>>>>\n>>>> What kind of protection violation we want to prevent?\n>>>>\n>>>> It seems to be obvious that normal user should not be able to prevent\n>>>> trigger execution because this triggers may be used to enforce some\n>>>> security policies.\n>>>> If trigger was created by user itself, then it can drop or disable it\n>>>> using ALTER statement. GUC is not needed for it.\n>>>>\n>>>\n>>> when you cannot connect to the database, then you cannot do ALTER. In\n>>> DBaaS environments lot of users has not superuser rights.\n>>>\n>>>\n>>>\n>>> But only superusers can set login triggers, right?\n>>> So only superuser can make a mistake in this trigger. But he have enough\n>>> rights to recover this error. Normal users are not able to define on\n>>> connection triggers and\n>>> should not have rights to disable them.\n>>>\n>>\n>> yes, it is true\n>>\n>> Pavel\n>>\n>>\n>>> --\n>>> Konstantin Knizhnik\n>>> Postgres Professional: http://www.postgrespro.com\n>>> The Russian Postgres Company\n>>>\n>>>\n>> So what's next?\n>> I see three options:\n>>\n>> 1. Do not introduce GUC for disabling all event triggers (especially\n>> taken in account that them are disabled by default).\n>> Return back to the patch\n>> on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch with\n>> \"disable_client_connection_trigger\"\n>> and make it true by default (to eliminate any overhead for users which\n>> are not using on logintriggers).\n>>\n>> 2. Have two GUCS: \"disable_client_connection_trigger\" and\n>> \"disable_event_triggers\".\n>>\n>> 3. Implement some mechanism for caching presence of event triggers in\n>> shared memory.\n>>\n>\n> @3 is the best design (the things should work well by default), @2 is a\n> little bit chaotic and @1 looks like a workaround.\n>\n>\n> Please notice that we still need GUC to disable on-login triggers: to make\n> it possible for superuser who did mistake and defined incorrect on-login\n> trigger to\n> login to the system.\n> Do we need GUC to disable all other event triggers? May be I am wrong, but\n> I do not see much need in such GUC: error in any of such event triggers is\n> non fatal\n> and can be easily reverted.\n> So the only question is whether \"disable_client_connection_trigger\" should\n> be true by default or not...\n>\n\n> I agree with you that @2 is a little bit chaotic and @1 looks like a\n> workaround.\n> But from my point of view @3 is not the best solution but overkill:\n> maintaining yet another shared hash just to save few milliseconds on login\n> seems to be too high price.\n> Actually there are many things which are loaded by new backend from the\n> database on start: for example - catalog.\n> This is why launch of new backend is an expensive operation.\n> Certainly if we execute \"select 1\", then system catalog is not needed...\n> But does anybody start new backend just to execute \"select 1\" and exit?\n>\n\n This is the worst case but tested on a not too bad CPU (i7). In virtual\nenvironments with overloaded CPU the effect can be worse.\n\n\n\n>\n>\n>\n>\n>\n>\n> Regards\n>\n> Pavel\n>\n>\n>>\n>> --\n>> Konstantin Knizhnik\n>> Postgres Professional: http://www.postgrespro.com\n>> The Russian Postgres Company\n>>\n>>\n> --\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>\n\nút 15. 12. 2020 v 15:06 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n\n\nOn 15.12.2020 16:18, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\nút 15. 12. 2020 v 14:12\n odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n \n\nOn 11.12.2020 19:27, Pavel Stehule wrote:\n\n\n\n\n\n\n\npá 11. 12. 2020\n v 17:05 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n \n\nOn 11.12.2020 18:40, Pavel Stehule wrote:\n\n\n\n\n\n is not correct.\n It makes it not possible to superuser\n to disable triggers for all users.\n\n\n\n\npg_database_ownercheck returns true\n for superuser always.\n\n\n\n\n Sorry, but I consider different case: when\n normal user is connected to the database.\n In this case pg_database_ownercheck returns\n false and trigger is not disabled, isn't it?\n\n\n\n\nMy idea was to reduce necessary rights to\n database owners.  But you have a true, so only\n superuser can create event trigger, so this\n feature cannot be used in DBaaS environments, and\n then my original idea was wrong.\n\n\n\n \n\n\n\n \n\n\n Also GUCs are\n not associated with any database. So I\n do not understand why  this check of\n database ownership is relevant at all?\n\n What kind of protection violation we\n want to prevent?\n\n It seems to be obvious that normal\n user should not be able to prevent\n trigger execution because this\n triggers may be used to enforce some\n security policies.\n If trigger was created by user itself,\n then it can drop or disable it using\n ALTER statement. GUC is not needed for\n it.\n\n\n\n\nwhen you cannot connect to the\n database, then you cannot do ALTER. In\n DBaaS environments lot of users has not\n superuser rights.\n\n\n\n\n\n\n But only superusers can set login triggers,\n right? \n So only superuser can make a mistake in this\n trigger. But he have enough rights to recover\n this error. Normal users are not able to define\n on connection triggers and \n should not have rights to disable them.\n\n\n\n\nyes, it is true\n\n\nPavel\n\n\n\n \n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company \n\n\n\n\n\n\n So what's next?\n I see three options:\n\n 1. Do not introduce GUC for disabling all event triggers\n (especially taken in account that them are  disabled by\n default).\n Return back to the patch\n on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch with\n \"disable_client_connection_trigger\"\n and make it true by default (to eliminate any overhead for\n users which are not using on logintriggers).\n\n 2. Have two GUCS: \"disable_client_connection_trigger\" and\n \"disable_event_triggers\".\n\n 3. Implement some mechanism for caching presence of event\n triggers in shared memory.\n\n\n\n\n@3 is the best design (the things should work well by\n default), @2 is a little bit chaotic and @1 looks like a\n workaround.\n\n\n\n\n\n\n Please notice that we still need GUC to disable on-login triggers:\n to make it possible for superuser who did mistake and defined\n incorrect on-login trigger to\n login to the system.\n Do we need GUC to disable all other event triggers? May be I am\n wrong, but I do not see much need in such GUC: error in any of such\n event triggers is non fatal\n and can be easily reverted.\n So the only question is whether \"disable_client_connection_trigger\"\n should be true by default or not... \n\n I agree with you that @2 is a little bit chaotic and @1 looks like a\n workaround.\n But from my point of view @3 is not the best solution but overkill:\n maintaining yet another shared hash just to save few milliseconds on\n login seems to be too high price.\n Actually there are many things which are loaded by new backend from\n the database on start: for example - catalog. \n This is why launch of new backend is an expensive operation. \n Certainly if we execute \"select 1\", then system catalog is not\n needed...\n But does anybody start new backend just to execute \"select 1\" and\n exit? This is the worst case but tested on a not too bad CPU (i7). In virtual environments with overloaded CPU the effect can be worse.  \n\n\n\n\n\n\n\n\n\nRegards\n\n\nPavel\n\n\n\n\n \n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company \n\n\n\n\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Tue, 15 Dec 2020 15:14:25 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "út 15. 12. 2020 v 15:06 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 15.12.2020 16:18, Pavel Stehule wrote:\n>\n>\n>\n> út 15. 12. 2020 v 14:12 odesílatel Konstantin Knizhnik <\n> k.knizhnik@postgrespro.ru> napsal:\n>\n>>\n>>\n>> On 11.12.2020 19:27, Pavel Stehule wrote:\n>>\n>>\n>>\n>> pá 11. 12. 2020 v 17:05 odesílatel Konstantin Knizhnik <\n>> k.knizhnik@postgrespro.ru> napsal:\n>>\n>>>\n>>>\n>>> On 11.12.2020 18:40, Pavel Stehule wrote:\n>>>\n>>>\n>>> is not correct. It makes it not possible to superuser to disable\n>>>> triggers for all users.\n>>>>\n>>>\n>>> pg_database_ownercheck returns true for superuser always.\n>>>\n>>>\n>>> Sorry, but I consider different case: when normal user is connected to\n>>> the database.\n>>> In this case pg_database_ownercheck returns false and trigger is not\n>>> disabled, isn't it?\n>>>\n>>\n>> My idea was to reduce necessary rights to database owners. But you have\n>> a true, so only superuser can create event trigger, so this feature cannot\n>> be used in DBaaS environments, and then my original idea was wrong.\n>>\n>>\n>>>\n>>> Also GUCs are not associated with any database. So I do not understand\n>>>> why this check of database ownership is relevant at all?\n>>>>\n>>>> What kind of protection violation we want to prevent?\n>>>>\n>>>> It seems to be obvious that normal user should not be able to prevent\n>>>> trigger execution because this triggers may be used to enforce some\n>>>> security policies.\n>>>> If trigger was created by user itself, then it can drop or disable it\n>>>> using ALTER statement. GUC is not needed for it.\n>>>>\n>>>\n>>> when you cannot connect to the database, then you cannot do ALTER. In\n>>> DBaaS environments lot of users has not superuser rights.\n>>>\n>>>\n>>>\n>>> But only superusers can set login triggers, right?\n>>> So only superuser can make a mistake in this trigger. But he have enough\n>>> rights to recover this error. Normal users are not able to define on\n>>> connection triggers and\n>>> should not have rights to disable them.\n>>>\n>>\n>> yes, it is true\n>>\n>> Pavel\n>>\n>>\n>>> --\n>>> Konstantin Knizhnik\n>>> Postgres Professional: http://www.postgrespro.com\n>>> The Russian Postgres Company\n>>>\n>>>\n>> So what's next?\n>> I see three options:\n>>\n>> 1. Do not introduce GUC for disabling all event triggers (especially\n>> taken in account that them are disabled by default).\n>> Return back to the patch\n>> on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch with\n>> \"disable_client_connection_trigger\"\n>> and make it true by default (to eliminate any overhead for users which\n>> are not using on logintriggers).\n>>\n>> 2. Have two GUCS: \"disable_client_connection_trigger\" and\n>> \"disable_event_triggers\".\n>>\n>> 3. Implement some mechanism for caching presence of event triggers in\n>> shared memory.\n>>\n>\n> @3 is the best design (the things should work well by default), @2 is a\n> little bit chaotic and @1 looks like a workaround.\n>\n>\n> Please notice that we still need GUC to disable on-login triggers: to make\n> it possible for superuser who did mistake and defined incorrect on-login\n> trigger to\n> login to the system.\n> Do we need GUC to disable all other event triggers? May be I am wrong, but\n> I do not see much need in such GUC: error in any of such event triggers is\n> non fatal\n> and can be easily reverted.\n> So the only question is whether \"disable_client_connection_trigger\" should\n> be true by default or not...\n>\n> I agree with you that @2 is a little bit chaotic and @1 looks like a\n> workaround.\n> But from my point of view @3 is not the best solution but overkill:\n> maintaining yet another shared hash just to save few milliseconds on login\n> seems to be too high price.\n> Actually there are many things which are loaded by new backend from the\n> database on start: for example - catalog.\n> This is why launch of new backend is an expensive operation.\n> Certainly if we execute \"select 1\", then system catalog is not needed...\n> But does anybody start new backend just to execute \"select 1\" and exit?\n>\n>\n>\nI understand so the implementation of a new shared cache can be a lot of\nwork. The best way is enhancing pg_database about one column with\ninformation about the login triggers (dathaslogontriggers). In init time\nthese data are in syscache, and can be easily checked. Some like\npg_attribute have an atthasdef column. Same fields has pg_class -\nrelhasrules, relhastriggers, ... Then the overhead of this design should be\nreally zero.\n\nWhat do you think about it?\n\nPavel\n\n\n>\n>\n>\n>\n> Regards\n>\n> Pavel\n>\n>\n>>\n>> --\n>> Konstantin Knizhnik\n>> Postgres Professional: http://www.postgrespro.com\n>> The Russian Postgres Company\n>>\n>>\n> --\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>\n\nút 15. 12. 2020 v 15:06 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n\n\nOn 15.12.2020 16:18, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\nút 15. 12. 2020 v 14:12\n odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n \n\nOn 11.12.2020 19:27, Pavel Stehule wrote:\n\n\n\n\n\n\n\npá 11. 12. 2020\n v 17:05 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n \n\nOn 11.12.2020 18:40, Pavel Stehule wrote:\n\n\n\n\n\n is not correct.\n It makes it not possible to superuser\n to disable triggers for all users.\n\n\n\n\npg_database_ownercheck returns true\n for superuser always.\n\n\n\n\n Sorry, but I consider different case: when\n normal user is connected to the database.\n In this case pg_database_ownercheck returns\n false and trigger is not disabled, isn't it?\n\n\n\n\nMy idea was to reduce necessary rights to\n database owners.  But you have a true, so only\n superuser can create event trigger, so this\n feature cannot be used in DBaaS environments, and\n then my original idea was wrong.\n\n\n\n \n\n\n\n \n\n\n Also GUCs are\n not associated with any database. So I\n do not understand why  this check of\n database ownership is relevant at all?\n\n What kind of protection violation we\n want to prevent?\n\n It seems to be obvious that normal\n user should not be able to prevent\n trigger execution because this\n triggers may be used to enforce some\n security policies.\n If trigger was created by user itself,\n then it can drop or disable it using\n ALTER statement. GUC is not needed for\n it.\n\n\n\n\nwhen you cannot connect to the\n database, then you cannot do ALTER. In\n DBaaS environments lot of users has not\n superuser rights.\n\n\n\n\n\n\n But only superusers can set login triggers,\n right? \n So only superuser can make a mistake in this\n trigger. But he have enough rights to recover\n this error. Normal users are not able to define\n on connection triggers and \n should not have rights to disable them.\n\n\n\n\nyes, it is true\n\n\nPavel\n\n\n\n \n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company \n\n\n\n\n\n\n So what's next?\n I see three options:\n\n 1. Do not introduce GUC for disabling all event triggers\n (especially taken in account that them are  disabled by\n default).\n Return back to the patch\n on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch with\n \"disable_client_connection_trigger\"\n and make it true by default (to eliminate any overhead for\n users which are not using on logintriggers).\n\n 2. Have two GUCS: \"disable_client_connection_trigger\" and\n \"disable_event_triggers\".\n\n 3. Implement some mechanism for caching presence of event\n triggers in shared memory.\n\n\n\n\n@3 is the best design (the things should work well by\n default), @2 is a little bit chaotic and @1 looks like a\n workaround.\n\n\n\n\n\n\n Please notice that we still need GUC to disable on-login triggers:\n to make it possible for superuser who did mistake and defined\n incorrect on-login trigger to\n login to the system.\n Do we need GUC to disable all other event triggers? May be I am\n wrong, but I do not see much need in such GUC: error in any of such\n event triggers is non fatal\n and can be easily reverted.\n So the only question is whether \"disable_client_connection_trigger\"\n should be true by default or not...\n\n I agree with you that @2 is a little bit chaotic and @1 looks like a\n workaround.\n But from my point of view @3 is not the best solution but overkill:\n maintaining yet another shared hash just to save few milliseconds on\n login seems to be too high price.\n Actually there are many things which are loaded by new backend from\n the database on start: for example - catalog. \n This is why launch of new backend is an expensive operation. \n Certainly if we execute \"select 1\", then system catalog is not\n needed...\n But does anybody start new backend just to execute \"select 1\" and\n exit?\n\nI understand so the implementation of a new shared cache can be a lot of work. The best way is enhancing pg_database about one column with information about the login triggers (dathaslogontriggers). In init time these data are in syscache, and can be easily checked. Some like pg_attribute have an atthasdef column.  Same fields has pg_class - relhasrules, relhastriggers, ... Then the overhead of this design should be really zero.What do you think about it?Pavel \n\n\n\n\n\n\n\nRegards\n\n\nPavel\n\n\n\n\n \n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company \n\n\n\n\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Tue, 15 Dec 2020 16:25:57 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 15.12.2020 18:25, Pavel Stehule wrote:\n>\n>\n> út 15. 12. 2020 v 15:06 odesílatel Konstantin Knizhnik \n> <k.knizhnik@postgrespro.ru <mailto:k.knizhnik@postgrespro.ru>> napsal:\n>\n>\n>\n> On 15.12.2020 16:18, Pavel Stehule wrote:\n>>\n>>\n>> út 15. 12. 2020 v 14:12 odesílatel Konstantin Knizhnik\n>> <k.knizhnik@postgrespro.ru <mailto:k.knizhnik@postgrespro.ru>>\n>> napsal:\n>>\n>>\n>>\n>> On 11.12.2020 19:27, Pavel Stehule wrote:\n>>>\n>>>\n>>> pá 11. 12. 2020 v 17:05 odesílatel Konstantin Knizhnik\n>>> <k.knizhnik@postgrespro.ru\n>>> <mailto:k.knizhnik@postgrespro.ru>> napsal:\n>>>\n>>>\n>>>\n>>> On 11.12.2020 18:40, Pavel Stehule wrote:\n>>>>\n>>>> is not correct. It makes it not possible to\n>>>> superuser to disable triggers for all users.\n>>>>\n>>>>\n>>>> pg_database_ownercheck returns true for superuser always.\n>>>\n>>> Sorry, but I consider different case: when normal user\n>>> is connected to the database.\n>>> In this case pg_database_ownercheck returns false and\n>>> trigger is not disabled, isn't it?\n>>>\n>>>\n>>> My idea was to reduce necessary rights to database owners. \n>>> But you have a true, so only superuser can create event\n>>> trigger, so this feature cannot be used in DBaaS\n>>> environments, and then my original idea was wrong.\n>>>\n>>>\n>>>>\n>>>> Also GUCs are not associated with any database. So\n>>>> I do not understand why  this check of database\n>>>> ownership is relevant at all?\n>>>>\n>>>> What kind of protection violation we want to prevent?\n>>>>\n>>>> It seems to be obvious that normal user should not\n>>>> be able to prevent trigger execution because this\n>>>> triggers may be used to enforce some security policies.\n>>>> If trigger was created by user itself, then it can\n>>>> drop or disable it using ALTER statement. GUC is\n>>>> not needed for it.\n>>>>\n>>>>\n>>>> when you cannot connect to the database, then you\n>>>> cannot do ALTER. In DBaaS environments lot of users has\n>>>> not superuser rights.\n>>>\n>>>\n>>> But only superusers can set login triggers, right?\n>>> So only superuser can make a mistake in this trigger.\n>>> But he have enough rights to recover this error. Normal\n>>> users are not able to define on connection triggers and\n>>> should not have rights to disable them.\n>>>\n>>>\n>>> yes, it is true\n>>>\n>>> Pavel\n>>>\n>>>\n>>> -- \n>>> Konstantin Knizhnik\n>>> Postgres Professional:http://www.postgrespro.com\n>>> The Russian Postgres Company\n>>>\n>>\n>> So what's next?\n>> I see three options:\n>>\n>> 1. Do not introduce GUC for disabling all event triggers\n>> (especially taken in account that them are  disabled by default).\n>> Return back to the patch\n>> on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch with\n>> \"disable_client_connection_trigger\"\n>> and make it true by default (to eliminate any overhead for\n>> users which are not using on logintriggers).\n>>\n>> 2. Have two GUCS: \"disable_client_connection_trigger\" and\n>> \"disable_event_triggers\".\n>>\n>> 3. Implement some mechanism for caching presence of event\n>> triggers in shared memory.\n>>\n>>\n>> @3 is the best design (the things should work well by default),\n>> @2 is a little bit chaotic and @1 looks like a workaround.\n>>\n>\n> Please notice that we still need GUC to disable on-login triggers:\n> to make it possible for superuser who did mistake and defined\n> incorrect on-login trigger to\n> login to the system.\n> Do we need GUC to disable all other event triggers? May be I am\n> wrong, but I do not see much need in such GUC: error in any of\n> such event triggers is non fatal\n> and can be easily reverted.\n> So the only question is whether\n> \"disable_client_connection_trigger\" should be true by default or\n> not...\n>\n> I agree with you that @2 is a little bit chaotic and @1 looks like\n> a workaround.\n> But from my point of view @3 is not the best solution but\n> overkill: maintaining yet another shared hash just to save few\n> milliseconds on login seems to be too high price.\n> Actually there are many things which are loaded by new backend\n> from the database on start: for example - catalog.\n> This is why launch of new backend is an expensive operation.\n> Certainly if we execute \"select 1\", then system catalog is not\n> needed...\n> But does anybody start new backend just to execute \"select 1\" and\n> exit?\n>\n>\n>\n> I understand so the implementation of a new shared cache can be a lot \n> of work. The best way is enhancing pg_database about one column with \n> information about the login triggers (dathaslogontriggers). In init \n> time these data are in syscache, and can be easily checked. Some like \n> pg_attribute have an atthasdef column.  Same fields has pg_class - \n> relhasrules, relhastriggers, ... Then the overhead of this design \n> should be really zero.\n>\n> What do you think about it?\n>\nI like this approach more than implementation of shared hash.\nBut still I have some concerns:\n\n1. pg_database table format has to be changed. Certainly it is not \nsomething  completely unacceptable. But IMHO we should try to avoid\nmodification of such commonly used catalog tables as much as possible.\n\n2. It is not so easy to maintain this flag. There can be multiple \non-login triggers defined. If such trigger is dropped, we can not just \nclear this flag.\nWe should check if other triggers exist. Now assume that there are two \ntriggers and two concurrent transactions dropping each one.\nAccording to their snapshots them do not see changes made by other \ntransaction. So them remove both triggers but didn't clear the flag.\nCertainly we can use counter instead of flag. But I am not sure that \ntheir will be not other problems with maintaining counter.\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n\n\n\n\n\n\nOn 15.12.2020 18:25, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\n\nút 15. 12. 2020 v 15:06\n odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n \n\nOn 15.12.2020 16:18, Pavel Stehule wrote:\n\n\n\n\n\n\n\nút 15. 12. 2020\n v 14:12 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n \n\nOn 11.12.2020 19:27, Pavel Stehule wrote:\n\n\n\n\n\n\n\npá 11.\n 12. 2020 v 17:05 odesílatel Konstantin\n Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n \n\nOn 11.12.2020 18:40, Pavel\n Stehule wrote:\n\n\n\n\n\n is not\n correct. It makes it not\n possible to superuser to\n disable triggers for all\n users.\n\n\n\n\npg_database_ownercheck\n returns true for superuser\n always.\n\n\n\n\n Sorry, but I consider different case:\n when normal user is connected to the\n database.\n In this case pg_database_ownercheck\n returns false and trigger is not\n disabled, isn't it?\n\n\n\n\nMy idea was to reduce necessary\n rights to database owners.  But you have\n a true, so only superuser can create\n event trigger, so this feature cannot be\n used in DBaaS environments, and then my\n original idea was wrong.\n\n\n\n \n\n\n\n \n\n\n Also\n GUCs are not associated with\n any database. So I do not\n understand why  this check\n of database ownership is\n relevant at all?\n\n What kind of protection\n violation we want to\n prevent?\n\n It seems to be obvious that\n normal user should not be\n able to prevent trigger\n execution because this\n triggers may be used to\n enforce some security\n policies.\n If trigger was created by\n user itself, then it can\n drop or disable it using\n ALTER statement. GUC is not\n needed for it.\n\n\n\n\nwhen you cannot connect to\n the database, then you cannot\n do ALTER. In DBaaS\n environments lot of users has\n not superuser rights.\n\n\n\n\n\n\n But only superusers can set login\n triggers, right? \n So only superuser can make a mistake\n in this trigger. But he have enough\n rights to recover this error. Normal\n users are not able to define on\n connection triggers and \n should not have rights to disable\n them.\n\n\n\n\nyes, it is true\n\n\nPavel\n\n\n\n \n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company \n\n\n\n\n\n\n So what's next?\n I see three options:\n\n 1. Do not introduce GUC for disabling all event\n triggers (especially taken in account that them\n are  disabled by default).\n Return back to the patch\n on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch\n with \"disable_client_connection_trigger\"\n and make it true by default (to eliminate any\n overhead for users which are not using on\n logintriggers).\n\n 2. Have two GUCS:\n \"disable_client_connection_trigger\" and\n \"disable_event_triggers\".\n\n 3. Implement some mechanism for caching presence\n of event triggers in shared memory.\n\n\n\n\n@3 is the best design (the things should work\n well by default), @2 is a little bit chaotic and\n @1 looks like a workaround.\n\n\n\n\n\n\n Please notice that we still need GUC to disable on-login\n triggers: to make it possible for superuser who did\n mistake and defined incorrect on-login trigger to\n login to the system.\n Do we need GUC to disable all other event triggers? May be\n I am wrong, but I do not see much need in such GUC: error\n in any of such event triggers is non fatal\n and can be easily reverted.\n So the only question is whether\n \"disable_client_connection_trigger\" should be true by\n default or not...\n\n I agree with you that @2 is a little bit chaotic and @1\n looks like a workaround.\n But from my point of view @3 is not the best solution but\n overkill: maintaining yet another shared hash just to save\n few milliseconds on login seems to be too high price.\n Actually there are many things which are loaded by new\n backend from the database on start: for example - catalog.\n \n This is why launch of new backend is an expensive\n operation. \n Certainly if we execute \"select 1\", then system catalog is\n not needed...\n But does anybody start new backend just to execute \"select\n 1\" and exit?\n\n\n\n\n\n\nI understand so the implementation of a new shared cache\n can be a lot of work. The best way is enhancing pg_database\n about one column with information about the login triggers\n (dathaslogontriggers). In init time these data are in\n syscache, and can be easily checked. Some like pg_attribute\n have an atthasdef column.  Same fields has pg_class -\n relhasrules, relhastriggers, ... Then the overhead of this\n design should be really zero.\n\n\n\nWhat do you think about it?\n\n\n\n\n\n\n I like this approach more than implementation of shared hash.\n But still I have some concerns:\n\n 1. pg_database table format has to be changed. Certainly it is not\n something  completely unacceptable. But IMHO we should try to avoid\n modification of such commonly used catalog tables as much as\n possible.\n\n 2. It is not so easy to maintain this flag. There can be multiple\n on-login triggers defined. If such trigger is dropped, we can not\n just clear this flag.\n We should check if other triggers exist. Now assume that there are\n two triggers and two concurrent transactions dropping each one.\n According to their snapshots them do not see changes made by other\n transaction. So them remove both triggers but didn't clear the flag.\n Certainly we can use counter instead of flag. But I am not sure that\n their will be not other problems with maintaining counter.\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Tue, 15 Dec 2020 19:42:39 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> Please notice that we still need GUC to disable on-login triggers: to make\n>> it possible for superuser who did mistake and defined incorrect on-login\n>> trigger to\n>> login to the system.\n>> Do we need GUC to disable all other event triggers? May be I am wrong,\n>> but I do not see much need in such GUC: error in any of such event triggers\n>> is non fatal\n>> and can be easily reverted.\n>> So the only question is whether \"disable_client_connection_trigger\"\n>> should be true by default or not...\n>>\n>> I agree with you that @2 is a little bit chaotic and @1 looks like a\n>> workaround.\n>> But from my point of view @3 is not the best solution but overkill:\n>> maintaining yet another shared hash just to save few milliseconds on login\n>> seems to be too high price.\n>> Actually there are many things which are loaded by new backend from the\n>> database on start: for example - catalog.\n>> This is why launch of new backend is an expensive operation.\n>> Certainly if we execute \"select 1\", then system catalog is not needed...\n>> But does anybody start new backend just to execute \"select 1\" and exit?\n>>\n>>\n>>\n> I understand so the implementation of a new shared cache can be a lot of\n> work. The best way is enhancing pg_database about one column with\n> information about the login triggers (dathaslogontriggers). In init time\n> these data are in syscache, and can be easily checked. Some like\n> pg_attribute have an atthasdef column. Same fields has pg_class -\n> relhasrules, relhastriggers, ... Then the overhead of this design should be\n> really zero.\n>\n> What do you think about it?\n>\n> I like this approach more than implementation of shared hash.\n> But still I have some concerns:\n>\n> 1. pg_database table format has to be changed. Certainly it is not\n> something completely unacceptable. But IMHO we should try to avoid\n> modification of such commonly used catalog tables as much as possible.\n>\n\nyes, I know. Unfortunately I don't see any other and correct solution.\nThere should be more wide discussion before this work about this topic. On\nsecond hand, this change should not break anything (if this new field will\nbe placed on as the last field). The logon trigger really looks like a\ndatabase trigger - so I think so this semantic is correct. I have no idea\nif it is acceptable for committers :-/. I hope so.\n\nThe fact that the existence of a logon trigger can be visible from a shared\ndatabase object can be an interesting feature too.\n\n\n> 2. It is not so easy to maintain this flag. There can be multiple on-login\n> triggers defined. If such trigger is dropped, we can not just clear this\n> flag.\n> We should check if other triggers exist. Now assume that there are two\n> triggers and two concurrent transactions dropping each one.\n> According to their snapshots them do not see changes made by other\n> transaction. So them remove both triggers but didn't clear the flag.\n> Certainly we can use counter instead of flag. But I am not sure that their\n> will be not other problems with maintaining counter.\n>\n\nI don't think it is necessary. My opinion is not too strong, but if\npg_class doesn't need to hold a number of triggers, then I think so\npg_database doesn't need to hold this number too.\n\n\n> --\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>\n\n\n Please notice that we still need GUC to disable on-login\n triggers: to make it possible for superuser who did\n mistake and defined incorrect on-login trigger to\n login to the system.\n Do we need GUC to disable all other event triggers? May be\n I am wrong, but I do not see much need in such GUC: error\n in any of such event triggers is non fatal\n and can be easily reverted.\n So the only question is whether\n \"disable_client_connection_trigger\" should be true by\n default or not...\n\n I agree with you that @2 is a little bit chaotic and @1\n looks like a workaround.\n But from my point of view @3 is not the best solution but\n overkill: maintaining yet another shared hash just to save\n few milliseconds on login seems to be too high price.\n Actually there are many things which are loaded by new\n backend from the database on start: for example - catalog.\n \n This is why launch of new backend is an expensive\n operation. \n Certainly if we execute \"select 1\", then system catalog is\n not needed...\n But does anybody start new backend just to execute \"select\n 1\" and exit?\n\n\n\n\n\n\nI understand so the implementation of a new shared cache\n can be a lot of work. The best way is enhancing pg_database\n about one column with information about the login triggers\n (dathaslogontriggers). In init time these data are in\n syscache, and can be easily checked. Some like pg_attribute\n have an atthasdef column.  Same fields has pg_class -\n relhasrules, relhastriggers, ... Then the overhead of this\n design should be really zero.\n\n\n\nWhat do you think about it?\n\n\n\n\n\n\n I like this approach more than implementation of shared hash.\n But still I have some concerns:\n\n 1. pg_database table format has to be changed. Certainly it is not\n something  completely unacceptable. But IMHO we should try to avoid\n modification of such commonly used catalog tables as much as\n possible.yes, I know. Unfortunately I  don't see any other and correct solution. There should be more wide discussion before this work about this topic. On second hand, this change should not break anything (if this new field will be placed on as the last field). The logon trigger really looks like a database trigger - so I think so this semantic is correct. I have no idea if it is acceptable for committers :-/. I hope so.  The fact that the existence of a logon trigger can be visible from a shared database object can be an interesting feature too.\n\n 2. It is not so easy to maintain this flag. There can be multiple\n on-login triggers defined. If such trigger is dropped, we can not\n just clear this flag.\n We should check if other triggers exist. Now assume that there are\n two triggers and two concurrent transactions dropping each one.\n According to their snapshots them do not see changes made by other\n transaction. So them remove both triggers but didn't clear the flag.\n Certainly we can use counter instead of flag. But I am not sure that\n their will be not other problems with maintaining counter.I don't think it is necessary.  My opinion is not too strong, but if pg_class doesn't need to hold a number of triggers, then I think so pg_database doesn't need to hold this number too. \n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Tue, 15 Dec 2020 18:16:47 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 15.12.2020 20:16, Pavel Stehule wrote:\n>\n>> Please notice that we still need GUC to disable on-login\n>> triggers: to make it possible for superuser who did mistake\n>> and defined incorrect on-login trigger to\n>> login to the system.\n>> Do we need GUC to disable all other event triggers? May be I\n>> am wrong, but I do not see much need in such GUC: error in\n>> any of such event triggers is non fatal\n>> and can be easily reverted.\n>> So the only question is whether\n>> \"disable_client_connection_trigger\" should be true by default\n>> or not...\n>>\n>> I agree with you that @2 is a little bit chaotic and @1 looks\n>> like a workaround.\n>> But from my point of view @3 is not the best solution but\n>> overkill: maintaining yet another shared hash just to save\n>> few milliseconds on login seems to be too high price.\n>> Actually there are many things which are loaded by new\n>> backend from the database on start: for example - catalog.\n>> This is why launch of new backend is an expensive operation.\n>> Certainly if we execute \"select 1\", then system catalog is\n>> not needed...\n>> But does anybody start new backend just to execute \"select 1\"\n>> and exit?\n>>\n>>\n>>\n>> I understand so the implementation of a new shared cache can be a\n>> lot of work. The best way is enhancing pg_database about one\n>> column with information about the login triggers\n>> (dathaslogontriggers). In init time these data are in syscache,\n>> and can be easily checked. Some like pg_attribute have an\n>> atthasdef column.  Same fields has pg_class - relhasrules,\n>> relhastriggers, ... Then the overhead of this design should be\n>> really zero.\n>>\n>> What do you think about it?\n>>\n> I like this approach more than implementation of shared hash.\n> But still I have some concerns:\n>\n> 1. pg_database table format has to be changed. Certainly it is not\n> something  completely unacceptable. But IMHO we should try to avoid\n> modification of such commonly used catalog tables as much as possible.\n>\n>\n> yes, I know. Unfortunately I  don't see any other and correct \n> solution. There should be more wide discussion before this work about \n> this topic. On second hand, this change should not break anything (if \n> this new field will be placed on as the last field). The logon trigger \n> really looks like a database trigger - so I think so this semantic is \n> correct. I have no idea if it is acceptable for committers :-/. I hope \n> so.\n>\n> The fact that the existence of a logon trigger can be visible from a \n> shared database object can be an interesting feature too.\n>\n>\n> 2. It is not so easy to maintain this flag. There can be multiple\n> on-login triggers defined. If such trigger is dropped, we can not\n> just clear this flag.\n> We should check if other triggers exist. Now assume that there are\n> two triggers and two concurrent transactions dropping each one.\n> According to their snapshots them do not see changes made by other\n> transaction. So them remove both triggers but didn't clear the flag.\n> Certainly we can use counter instead of flag. But I am not sure\n> that their will be not other problems with maintaining counter.\n>\n>\n> I don't think it is necessary.  My opinion is not too strong, but if \n> pg_class doesn't need to hold a number of triggers, then I think so \n> pg_database doesn't need to hold this number too.\n>\nAttached please find new versoin of the patch based on \non_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch\nSo there is still only  \"disable_client_connection_trigger\" GUC? because \nwe need possibility to disable client connect triggers and there is no \nsuch need for other event types.\n\nAs you suggested  have added \"dathaslogontriggers\" flag which is set \nwhen client connection trigger is created.\nThis flag is never cleaned (to avoid visibility issues mentioned in my \nprevious mail).\n\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Wed, 16 Dec 2020 16:35:35 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Attached please find new versoin of the patch based on\non_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch\n\n> So there is still only \"disable_client_connection_trigger\" GUC? because\n> we need possibility to disable client connect triggers and there is no such\n> need for other event types.\n>\n> As you suggested have added \"dathaslogontriggers\" flag which is set when\n> client connection trigger is created.\n> This flag is never cleaned (to avoid visibility issues mentioned in my\n> previous mail).\n>\n\nThis is much better - I don't see any slowdown when logon trigger is not\ndefined\n\nI did some benchmarks and looks so starting language handler is relatively\nexpensive - it is about 25% and starting handler like event trigger has\nabout 35%. But this problem can be solved later and elsewhere.\n\nI prefer the inverse form of disable_connection_trigger. Almost all GUC are\nin positive form - so enable_connection_triggger is better\n\nI don't think so current handling dathaslogontriggers is good for\nproduction usage. The protection against race condition can be solved by\nlock on pg_event_trigger\n\nRegards\n\nPavel\n\n\n\n>\n>\n> --\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>\n\nAttached please find new versoin of the patch based on\n on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch\n So there is still only  \"disable_client_connection_trigger\" GUC?\n because we need possibility to disable client connect triggers and\n there is no such need for other event types.\n\n As you suggested  have added \"dathaslogontriggers\" flag which is set\n when client connection trigger is created.\n This flag is never cleaned (to avoid visibility issues mentioned in\n my previous mail). This is much better - I don't see any slowdown when logon trigger is not definedI did some benchmarks and looks so starting language handler is relatively expensive - it is about 25% and starting handler like event trigger has about 35%. But this problem can be solved later and elsewhere.I prefer the inverse form of disable_connection_trigger. Almost all GUC are in positive form - so enable_connection_triggger is betterI don't think so current handling dathaslogontriggers is good for production usage. The protection against race condition can be solved by lock on pg_event_triggerRegardsPavel\n\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Wed, 16 Dec 2020 20:38:06 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "st 16. 12. 2020 v 20:38 odesílatel Pavel Stehule <pavel.stehule@gmail.com>\nnapsal:\n\n> Attached please find new versoin of the patch based on\n> on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch\n>\n>> So there is still only \"disable_client_connection_trigger\" GUC? because\n>> we need possibility to disable client connect triggers and there is no such\n>> need for other event types.\n>>\n>> As you suggested have added \"dathaslogontriggers\" flag which is set when\n>> client connection trigger is created.\n>> This flag is never cleaned (to avoid visibility issues mentioned in my\n>> previous mail).\n>>\n>\n> This is much better - I don't see any slowdown when logon trigger is not\n> defined\n>\n> I did some benchmarks and looks so starting language handler is relatively\n> expensive - it is about 25% and starting handler like event trigger has\n> about 35%. But this problem can be solved later and elsewhere.\n>\n> I prefer the inverse form of disable_connection_trigger. Almost all GUC\n> are in positive form - so enable_connection_triggger is better\n>\n> I don't think so current handling dathaslogontriggers is good for\n> production usage. The protection against race condition can be solved by\n> lock on pg_event_trigger\n>\n\nI thought about it, and probably the counter of connect triggers will be\nbetter there. The implementation will be simpler and more robust.\n\nPavel\n\n\n> Regards\n>\n> Pavel\n>\n>\n>\n>>\n>>\n>> --\n>> Konstantin Knizhnik\n>> Postgres Professional: http://www.postgrespro.com\n>> The Russian Postgres Company\n>>\n>>\n\nst 16. 12. 2020 v 20:38 odesílatel Pavel Stehule <pavel.stehule@gmail.com> napsal:Attached please find new versoin of the patch based on\n on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch\n So there is still only  \"disable_client_connection_trigger\" GUC?\n because we need possibility to disable client connect triggers and\n there is no such need for other event types.\n\n As you suggested  have added \"dathaslogontriggers\" flag which is set\n when client connection trigger is created.\n This flag is never cleaned (to avoid visibility issues mentioned in\n my previous mail). This is much better - I don't see any slowdown when logon trigger is not definedI did some benchmarks and looks so starting language handler is relatively expensive - it is about 25% and starting handler like event trigger has about 35%. But this problem can be solved later and elsewhere.I prefer the inverse form of disable_connection_trigger. Almost all GUC are in positive form - so enable_connection_triggger is betterI don't think so current handling dathaslogontriggers is good for production usage. The protection against race condition can be solved by lock on pg_event_triggerI thought about it, and probably the counter of connect triggers will be better there. The implementation will be simpler and more robust.PavelRegardsPavel\n\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Thu, 17 Dec 2020 07:31:45 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 17.12.2020 9:31, Pavel Stehule wrote:\n>\n>\n> st 16. 12. 2020 v 20:38 odesílatel Pavel Stehule \n> <pavel.stehule@gmail.com <mailto:pavel.stehule@gmail.com>> napsal:\n>\n> Attached please find new versoin of the patch based on\n> on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch\n>\n> So there is still only \"disable_client_connection_trigger\"\n> GUC? because we need possibility to disable client connect\n> triggers and there is no such need for other event types.\n>\n> As you suggested  have added \"dathaslogontriggers\" flag which\n> is set when client connection trigger is created.\n> This flag is never cleaned (to avoid visibility issues\n> mentioned in my previous mail).\n>\n>\n> This is much better - I don't see any slowdown when logon trigger\n> is not defined\n>\n> I did some benchmarks and looks so starting language handler is\n> relatively expensive - it is about 25% and starting handler like\n> event trigger has about 35%. But this problem can be solved later\n> and elsewhere.\n>\n> I prefer the inverse form of disable_connection_trigger. Almost\n> all GUC are in positive form - so enable_connection_triggger is better\n>\n> I don't think so current handling dathaslogontriggers is good for\n> production usage. The protection against race condition can be\n> solved by lock on pg_event_trigger\n>\n>\n> I thought about it, and probably the counter of connect triggers will \n> be better there. The implementation will be simpler and more robust.\n>\n>\n\n\nI prefer to implement different approach: unset dathaslogontriggers flag \nin event trigger itself when no triggers are returned by \nEventTriggerCommonSetup.\nI am using double checking to prevent race condition.\nThe main reason for this approach is that dropping of triggers is not \ndone in event_trigger.c: it is done by generic code for all resources.\nIt seems to be there is no right place where decrementing of trigger \ncounters can be inserted.\nAlso I prefer to keep all logon-trigger specific code in one file.\n\nAlso, as you suggested, I renamed disable_connection_trigger to \nenable_connection_trigger.\n\n\nNew version of the patch is attached.\n\n\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Thu, 17 Dec 2020 16:03:56 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "čt 17. 12. 2020 v 14:04 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 17.12.2020 9:31, Pavel Stehule wrote:\n>\n>\n>\n> st 16. 12. 2020 v 20:38 odesílatel Pavel Stehule <pavel.stehule@gmail.com>\n> napsal:\n>\n>> Attached please find new versoin of the patch based on\n>> on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch\n>>\n>>> So there is still only \"disable_client_connection_trigger\" GUC? because\n>>> we need possibility to disable client connect triggers and there is no such\n>>> need for other event types.\n>>>\n>>> As you suggested have added \"dathaslogontriggers\" flag which is set\n>>> when client connection trigger is created.\n>>> This flag is never cleaned (to avoid visibility issues mentioned in my\n>>> previous mail).\n>>>\n>>\n>> This is much better - I don't see any slowdown when logon trigger is not\n>> defined\n>>\n>> I did some benchmarks and looks so starting language handler is\n>> relatively expensive - it is about 25% and starting handler like event\n>> trigger has about 35%. But this problem can be solved later and elsewhere.\n>>\n>> I prefer the inverse form of disable_connection_trigger. Almost all GUC\n>> are in positive form - so enable_connection_triggger is better\n>>\n>> I don't think so current handling dathaslogontriggers is good for\n>> production usage. The protection against race condition can be solved by\n>> lock on pg_event_trigger\n>>\n>\n> I thought about it, and probably the counter of connect triggers will be\n> better there. The implementation will be simpler and more robust.\n>\n>\n>\n>\n> I prefer to implement different approach: unset dathaslogontriggers flag\n> in event trigger itself when no triggers are returned by\n> EventTriggerCommonSetup.\n> I am using double checking to prevent race condition.\n> The main reason for this approach is that dropping of triggers is not done\n> in event_trigger.c: it is done by generic code for all resources.\n> It seems to be there is no right place where decrementing of trigger\n> counters can be inserted.\n> Also I prefer to keep all logon-trigger specific code in one file.\n>\n> Also, as you suggested, I renamed disable_connection_trigger to\n> enable_connection_trigger.\n>\n>\n> New version of the patch is attached.\n>\n\nyes, it can work\n\nRegards\n\nPavel\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\nčt 17. 12. 2020 v 14:04 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n\n\nOn 17.12.2020 9:31, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\nst 16. 12. 2020 v 20:38\n odesílatel Pavel Stehule <pavel.stehule@gmail.com>\n napsal:\n\n\nAttached please find new versoin of the patch\n based on\n on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch\n\n\n So there is still only \n \"disable_client_connection_trigger\" GUC? because we\n need possibility to disable client connect triggers\n and there is no such need for other event types.\n\n As you suggested  have added \"dathaslogontriggers\"\n flag which is set when client connection trigger is\n created.\n This flag is never cleaned (to avoid visibility\n issues mentioned in my previous mail). \n\n\n\n\nThis is much better - I don't see any slowdown when\n logon trigger is not defined\n\n\nI did some benchmarks and looks so starting\n language handler is relatively expensive - it is about\n 25% and starting handler like event trigger has about\n 35%. But this problem can be solved later and\n elsewhere.\n\n\n\nI prefer the inverse form of\n disable_connection_trigger. Almost all GUC are in\n positive form - so enable_connection_triggger is\n better\n\n\nI don't think so current handling\n dathaslogontriggers is good for production usage. The\n protection against race condition can be solved by\n lock on pg_event_trigger\n\n\n\n\n\nI thought about it, and probably the counter of connect\n triggers will be better there. The implementation will be\n simpler and more robust.\n\n\n\n\n\n\n\n\n I prefer to implement different approach: unset dathaslogontriggers \n flag in event trigger itself when no triggers are returned by\n EventTriggerCommonSetup.\n I am using double checking to prevent race condition.\n The main reason for this approach is that dropping of triggers is\n not done in event_trigger.c: it is done by generic code for all\n resources.\n It seems to be there is no right place where decrementing of trigger\n counters can be inserted.\n Also I prefer to keep all logon-trigger specific code in one file.\n\n Also, as you suggested, I renamed disable_connection_trigger to\n enable_connection_trigger.\n\n\n New version of the patch is attached.yes, it can workRegardsPavel \n\n\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Thu, 17 Dec 2020 19:30:41 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "čt 17. 12. 2020 v 19:30 odesílatel Pavel Stehule <pavel.stehule@gmail.com>\nnapsal:\n\n>\n>\n> čt 17. 12. 2020 v 14:04 odesílatel Konstantin Knizhnik <\n> k.knizhnik@postgrespro.ru> napsal:\n>\n>>\n>>\n>> On 17.12.2020 9:31, Pavel Stehule wrote:\n>>\n>>\n>>\n>> st 16. 12. 2020 v 20:38 odesílatel Pavel Stehule <pavel.stehule@gmail.com>\n>> napsal:\n>>\n>>> Attached please find new versoin of the patch based on\n>>> on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch\n>>>\n>>>> So there is still only \"disable_client_connection_trigger\" GUC?\n>>>> because we need possibility to disable client connect triggers and there is\n>>>> no such need for other event types.\n>>>>\n>>>> As you suggested have added \"dathaslogontriggers\" flag which is set\n>>>> when client connection trigger is created.\n>>>> This flag is never cleaned (to avoid visibility issues mentioned in my\n>>>> previous mail).\n>>>>\n>>>\n>>> This is much better - I don't see any slowdown when logon trigger is not\n>>> defined\n>>>\n>>> I did some benchmarks and looks so starting language handler is\n>>> relatively expensive - it is about 25% and starting handler like event\n>>> trigger has about 35%. But this problem can be solved later and elsewhere.\n>>>\n>>> I prefer the inverse form of disable_connection_trigger. Almost all GUC\n>>> are in positive form - so enable_connection_triggger is better\n>>>\n>>> I don't think so current handling dathaslogontriggers is good for\n>>> production usage. The protection against race condition can be solved by\n>>> lock on pg_event_trigger\n>>>\n>>\n>> I thought about it, and probably the counter of connect triggers will be\n>> better there. The implementation will be simpler and more robust.\n>>\n>>\n>>\n>>\n>> I prefer to implement different approach: unset dathaslogontriggers flag\n>> in event trigger itself when no triggers are returned by\n>> EventTriggerCommonSetup.\n>> I am using double checking to prevent race condition.\n>> The main reason for this approach is that dropping of triggers is not\n>> done in event_trigger.c: it is done by generic code for all resources.\n>> It seems to be there is no right place where decrementing of trigger\n>> counters can be inserted.\n>> Also I prefer to keep all logon-trigger specific code in one file.\n>>\n>> Also, as you suggested, I renamed disable_connection_trigger to\n>> enable_connection_trigger.\n>>\n>>\n>> New version of the patch is attached.\n>>\n>\n> yes, it can work\n>\n\nfor complete review the new field in pg_doc should be documented\n\nRegards\n\nPavel\n\n\n> Regards\n>\n> Pavel\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\nčt 17. 12. 2020 v 19:30 odesílatel Pavel Stehule <pavel.stehule@gmail.com> napsal:čt 17. 12. 2020 v 14:04 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n\n\nOn 17.12.2020 9:31, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\nst 16. 12. 2020 v 20:38\n odesílatel Pavel Stehule <pavel.stehule@gmail.com>\n napsal:\n\n\nAttached please find new versoin of the patch\n based on\n on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch\n\n\n So there is still only \n \"disable_client_connection_trigger\" GUC? because we\n need possibility to disable client connect triggers\n and there is no such need for other event types.\n\n As you suggested  have added \"dathaslogontriggers\"\n flag which is set when client connection trigger is\n created.\n This flag is never cleaned (to avoid visibility\n issues mentioned in my previous mail). \n\n\n\n\nThis is much better - I don't see any slowdown when\n logon trigger is not defined\n\n\nI did some benchmarks and looks so starting\n language handler is relatively expensive - it is about\n 25% and starting handler like event trigger has about\n 35%. But this problem can be solved later and\n elsewhere.\n\n\n\nI prefer the inverse form of\n disable_connection_trigger. Almost all GUC are in\n positive form - so enable_connection_triggger is\n better\n\n\nI don't think so current handling\n dathaslogontriggers is good for production usage. The\n protection against race condition can be solved by\n lock on pg_event_trigger\n\n\n\n\n\nI thought about it, and probably the counter of connect\n triggers will be better there. The implementation will be\n simpler and more robust.\n\n\n\n\n\n\n\n\n I prefer to implement different approach: unset dathaslogontriggers \n flag in event trigger itself when no triggers are returned by\n EventTriggerCommonSetup.\n I am using double checking to prevent race condition.\n The main reason for this approach is that dropping of triggers is\n not done in event_trigger.c: it is done by generic code for all\n resources.\n It seems to be there is no right place where decrementing of trigger\n counters can be inserted.\n Also I prefer to keep all logon-trigger specific code in one file.\n\n Also, as you suggested, I renamed disable_connection_trigger to\n enable_connection_trigger.\n\n\n New version of the patch is attached.yes, it can workfor complete review the new field in pg_doc should be documented RegardsPavelRegardsPavel \n\n\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Sun, 20 Dec 2020 08:04:04 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 20.12.2020 10:04, Pavel Stehule wrote:\n>\n>\n> čt 17. 12. 2020 v 19:30 odesílatel Pavel Stehule \n> <pavel.stehule@gmail.com <mailto:pavel.stehule@gmail.com>> napsal:\n>\n>\n>\n> čt 17. 12. 2020 v 14:04 odesílatel Konstantin Knizhnik\n> <k.knizhnik@postgrespro.ru <mailto:k.knizhnik@postgrespro.ru>> napsal:\n>\n>\n>\n> On 17.12.2020 9:31, Pavel Stehule wrote:\n>>\n>>\n>> st 16. 12. 2020 v 20:38 odesílatel Pavel Stehule\n>> <pavel.stehule@gmail.com <mailto:pavel.stehule@gmail.com>>\n>> napsal:\n>>\n>> Attached please find new versoin of the patch based on\n>> on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch\n>>\n>> So there is still only\n>> \"disable_client_connection_trigger\" GUC? because we\n>> need possibility to disable client connect triggers\n>> and there is no such need for other event types.\n>>\n>> As you suggested  have added \"dathaslogontriggers\"\n>> flag which is set when client connection trigger is\n>> created.\n>> This flag is never cleaned (to avoid visibility\n>> issues mentioned in my previous mail).\n>>\n>>\n>> This is much better - I don't see any slowdown when logon\n>> trigger is not defined\n>>\n>> I did some benchmarks and looks so starting language\n>> handler is relatively expensive - it is about 25% and\n>> starting handler like event trigger has about 35%. But\n>> this problem can be solved later and elsewhere.\n>>\n>> I prefer the inverse form of disable_connection_trigger.\n>> Almost all GUC are in positive form - so\n>> enable_connection_triggger is better\n>>\n>> I don't think so current handling dathaslogontriggers is\n>> good for production usage. The protection against race\n>> condition can be solved by lock on pg_event_trigger\n>>\n>>\n>> I thought about it, and probably the counter of connect\n>> triggers will be better there. The implementation will be\n>> simpler and more robust.\n>>\n>>\n>\n>\n> I prefer to implement different approach: unset\n> dathaslogontriggers  flag in event trigger itself when no\n> triggers are returned by EventTriggerCommonSetup.\n> I am using double checking to prevent race condition.\n> The main reason for this approach is that dropping of triggers\n> is not done in event_trigger.c: it is done by generic code for\n> all resources.\n> It seems to be there is no right place where decrementing of\n> trigger counters can be inserted.\n> Also I prefer to keep all logon-trigger specific code in one file.\n>\n> Also, as you suggested, I renamed disable_connection_trigger\n> to enable_connection_trigger.\n>\n>\n> New version of the patch is attached.\n>\n>\n> yes, it can work\n>\n>\n> for complete review the new field in pg_doc should be documented\n>\n\nDone.\nAlso I fixed some examples in documentation which involves pg_database.\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Mon, 21 Dec 2020 13:06:43 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi\n\npo 21. 12. 2020 v 11:06 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 20.12.2020 10:04, Pavel Stehule wrote:\n>\n>\n>\n> čt 17. 12. 2020 v 19:30 odesílatel Pavel Stehule <pavel.stehule@gmail.com>\n> napsal:\n>\n>>\n>>\n>> čt 17. 12. 2020 v 14:04 odesílatel Konstantin Knizhnik <\n>> k.knizhnik@postgrespro.ru> napsal:\n>>\n>>>\n>>>\n>>> On 17.12.2020 9:31, Pavel Stehule wrote:\n>>>\n>>>\n>>>\n>>> st 16. 12. 2020 v 20:38 odesílatel Pavel Stehule <\n>>> pavel.stehule@gmail.com> napsal:\n>>>\n>>>> Attached please find new versoin of the patch based on\n>>>> on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch\n>>>>\n>>>>> So there is still only \"disable_client_connection_trigger\" GUC?\n>>>>> because we need possibility to disable client connect triggers and there is\n>>>>> no such need for other event types.\n>>>>>\n>>>>> As you suggested have added \"dathaslogontriggers\" flag which is set\n>>>>> when client connection trigger is created.\n>>>>> This flag is never cleaned (to avoid visibility issues mentioned in my\n>>>>> previous mail).\n>>>>>\n>>>>\n>>>> This is much better - I don't see any slowdown when logon trigger is\n>>>> not defined\n>>>>\n>>>> I did some benchmarks and looks so starting language handler is\n>>>> relatively expensive - it is about 25% and starting handler like event\n>>>> trigger has about 35%. But this problem can be solved later and elsewhere.\n>>>>\n>>>> I prefer the inverse form of disable_connection_trigger. Almost all GUC\n>>>> are in positive form - so enable_connection_triggger is better\n>>>>\n>>>> I don't think so current handling dathaslogontriggers is good for\n>>>> production usage. The protection against race condition can be solved by\n>>>> lock on pg_event_trigger\n>>>>\n>>>\n>>> I thought about it, and probably the counter of connect triggers will be\n>>> better there. The implementation will be simpler and more robust.\n>>>\n>>>\n>>>\n>>>\n>>> I prefer to implement different approach: unset dathaslogontriggers\n>>> flag in event trigger itself when no triggers are returned by\n>>> EventTriggerCommonSetup.\n>>> I am using double checking to prevent race condition.\n>>> The main reason for this approach is that dropping of triggers is not\n>>> done in event_trigger.c: it is done by generic code for all resources.\n>>> It seems to be there is no right place where decrementing of trigger\n>>> counters can be inserted.\n>>> Also I prefer to keep all logon-trigger specific code in one file.\n>>>\n>>> Also, as you suggested, I renamed disable_connection_trigger to\n>>> enable_connection_trigger.\n>>>\n>>>\n>>> New version of the patch is attached.\n>>>\n>>\n>> yes, it can work\n>>\n>\n> for complete review the new field in pg_doc should be documented\n>\n>\n> Done.\n> Also I fixed some examples in documentation which involves pg_database.\n>\n\nregress tests fails\n\n sysviews ... FAILED 112 ms\ntest event_trigger ... FAILED (test process exited with exit\ncode 2) 447 ms\ntest fast_default ... FAILED 392 ms\ntest stats ... FAILED 626 ms\n============== shutting down postmaster ==============\n\nRegards\n\nPavel\n\n\n> --\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>\n\nHipo 21. 12. 2020 v 11:06 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n\n\nOn 20.12.2020 10:04, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\nčt 17. 12. 2020 v 19:30\n odesílatel Pavel Stehule <pavel.stehule@gmail.com>\n napsal:\n\n\n\n\n\n\n\nčt 17. 12. 2020\n v 14:04 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n \n\nOn 17.12.2020 9:31, Pavel Stehule wrote:\n\n\n\n\n\n\n\nst 16. 12.\n 2020 v 20:38 odesílatel Pavel Stehule <pavel.stehule@gmail.com>\n napsal:\n\n\nAttached please find new\n versoin of the patch based on\n on_connect_event_trigger_WITH_SUGGESTED_UPDATES.patch\n\n\n So there is\n still only \n \"disable_client_connection_trigger\"\n GUC? because we need possibility to\n disable client connect triggers and\n there is no such need for other\n event types.\n\n As you suggested  have added\n \"dathaslogontriggers\" flag which is\n set when client connection trigger\n is created.\n This flag is never cleaned (to avoid\n visibility issues mentioned in my\n previous mail). \n\n\n\n\nThis is much better - I don't see\n any slowdown when logon trigger is not\n defined\n\n\nI did some benchmarks and looks so\n starting language handler is\n relatively expensive - it is about 25%\n and starting handler like event\n trigger has about 35%. But this\n problem can be solved later and\n elsewhere.\n\n\n\nI prefer the inverse form of\n disable_connection_trigger. Almost all\n GUC are in positive form - so\n enable_connection_triggger is better\n\n\nI don't think so current handling\n dathaslogontriggers is good for\n production usage. The protection\n against race condition can be solved\n by lock on pg_event_trigger\n\n\n\n\n\nI thought about it, and probably the\n counter of connect triggers will be better\n there. The implementation will be simpler\n and more robust.\n\n\n\n\n\n\n\n\n I prefer to implement different approach: unset\n dathaslogontriggers  flag in event trigger itself\n when no triggers are returned by\n EventTriggerCommonSetup.\n I am using double checking to prevent race\n condition.\n The main reason for this approach is that dropping\n of triggers is not done in event_trigger.c: it is\n done by generic code for all resources.\n It seems to be there is no right place where\n decrementing of trigger counters can be inserted.\n Also I prefer to keep all logon-trigger specific\n code in one file.\n\n Also, as you suggested, I renamed\n disable_connection_trigger to\n enable_connection_trigger.\n\n\n New version of the patch is attached.\n\n\n\n\nyes, it can work\n\n\n\n\n\nfor complete review the new field in pg_doc should be\n documented \n\n\n\n\n\n\n\n Done. \n Also I fixed some examples in documentation which involves\n pg_database.regress tests fails      sysviews                     ... FAILED      112 mstest event_trigger                ... FAILED (test process exited with exit code 2)      447 mstest fast_default                 ... FAILED      392 mstest stats                        ... FAILED      626 ms============== shutting down postmaster               ==============RegardsPavel\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Tue, 22 Dec 2020 10:25:27 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 22.12.2020 12:25, Pavel Stehule wrote:\n>\n> regress tests fails\n>\n>      sysviews                     ... FAILED      112 ms\n> test event_trigger                ... FAILED (test process exited with \n> exit code 2)      447 ms\n> test fast_default                 ... FAILED      392 ms\n> test stats                        ... FAILED      626 ms\n> ============== shutting down postmaster ==============\n>\n\nSorry, fixed.\n\n\n> -- \n\nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Tue, 22 Dec 2020 14:42:49 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "út 22. 12. 2020 v 12:42 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 22.12.2020 12:25, Pavel Stehule wrote:\n>\n>\n> regress tests fails\n>\n> sysviews ... FAILED 112 ms\n> test event_trigger ... FAILED (test process exited with\n> exit code 2) 447 ms\n> test fast_default ... FAILED 392 ms\n> test stats ... FAILED 626 ms\n> ============== shutting down postmaster ==============\n>\n>\n> Sorry, fixed.\n>\n\nno problem\n\nI had to fix doc\n\ndiff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml\nindex 6ff783273f..7aded1848f 100644\n--- a/doc/src/sgml/config.sgml\n+++ b/doc/src/sgml/config.sgml\n@@ -1008,7 +1008,7 @@ include_dir 'conf.d'\n trigger when a client connects. This parameter is switched on by\ndefault.\n Errors in trigger code can prevent user to login to the system.\n I this case disabling this parameter in connection string can\nsolve the problem:\n- <literal>psql \"dbname=postgres options='-c\nenable_client_connection_trigger=false'\".\n+ <literal>psql \"dbname=postgres options='-c\nenable_client_connection_trigger=false'\"</literal>.\n </para>\n </listitem>\n </varlistentry>\n\nI am thinking again about enable_client_connection_trigger, and although it\ncan look useless (because error is ignored for superuser), it can be useful\nfor some debugging and administration purposes. Probably we don't want to\nstart the client_connection trigger from backup tools, maybe from some\nmonitoring tools. Maybe the possibility to set this GUC can be dedicated to\nsome special role (like pg_signal_backend).\n\n+ <varlistentry id=\"guc-enable-client-connection-trigger\"\nxreflabel=\"enable_client_connection_trigger\">\n+ <term><varname>enable_client_connection_trigger</varname>\n(<type>boolean</type>)\n+ <indexterm>\n+ <primary><varname>enable_client_connection_trigger</varname>\nconfiguration parameter</primary>\n+ </indexterm>\n+ </term>\n+ <listitem>\n+ <para>\n+ Enables firing the <literal>client_connection</literal>\n+ trigger when a client connects. This parameter is switched on by\ndefault.\n+ Errors in trigger code can prevent user to login to the system.\n+ I this case disabling this parameter in connection string can\nsolve the problem:\n+ <literal>psql \"dbname=postgres options='-c\nenable_client_connection_trigger=false'\"</literal>.\n+ </para>\n+ </listitem>\n+ </varlistentry>\n\nThere should be note, so only superuser can change this value\n\nThere is should be tab-complete support\n\ndiff --git a/src/bin/psql/tab-complete.c b/src/bin/psql/tab-complete.c\nindex 3a43c09bf6..08f00d8fc4 100644\n--- a/src/bin/psql/tab-complete.c\n+++ b/src/bin/psql/tab-complete.c\n@@ -2970,7 +2970,8 @@ psql_completion(const char *text, int start, int end)\n COMPLETE_WITH(\"ON\");\n /* Complete CREATE EVENT TRIGGER <name> ON with event_type */\n else if (Matches(\"CREATE\", \"EVENT\", \"TRIGGER\", MatchAny, \"ON\"))\n- COMPLETE_WITH(\"ddl_command_start\", \"ddl_command_end\", \"sql_drop\");\n+ COMPLETE_WITH(\"ddl_command_start\", \"ddl_command_end\",\n+ \"client_connection\", \"sql_drop\");\n\n /*\n * Complete CREATE EVENT TRIGGER <name> ON <event_type>. EXECUTE\nFUNCTION\n\nRegards\n\nPavel\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\nút 22. 12. 2020 v 12:42 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n\n\nOn 22.12.2020 12:25, Pavel Stehule\n wrote:\n\n\n\n\nregress tests fails\n\n\n      sysviews                     ... FAILED      112 ms\ntest event_trigger                ... FAILED (test\n process exited with exit code 2)      447 ms\n test fast_default                 ... FAILED      392 ms\n test stats                        ... FAILED      626 ms\n ============== shutting down postmaster              \n ==============\n\n\n\n\n\n\n Sorry, fixed.no problemI had to fix docdiff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgmlindex 6ff783273f..7aded1848f 100644--- a/doc/src/sgml/config.sgml+++ b/doc/src/sgml/config.sgml@@ -1008,7 +1008,7 @@ include_dir 'conf.d'         trigger when a client connects. This parameter is switched on by default.         Errors in trigger code can prevent user to login to the system.         I this case disabling this parameter in connection string can solve the problem:-        <literal>psql \"dbname=postgres options='-c enable_client_connection_trigger=false'\". +        <literal>psql \"dbname=postgres options='-c enable_client_connection_trigger=false'\"</literal>.        </para>       </listitem>      </varlistentry>I am thinking again about enable_client_connection_trigger, and although it can look useless (because error is ignored for superuser), it can be useful for some debugging and administration purposes. Probably we don't want to start the client_connection trigger from backup tools, maybe from some monitoring tools. Maybe the possibility to set this GUC can be dedicated to some special role (like pg_signal_backend). +     <varlistentry id=\"guc-enable-client-connection-trigger\" xreflabel=\"enable_client_connection_trigger\">+      <term><varname>enable_client_connection_trigger</varname> (<type>boolean</type>)+      <indexterm>+       <primary><varname>enable_client_connection_trigger</varname> configuration parameter</primary>+      </indexterm>+      </term>+      <listitem>+       <para>+        Enables firing the <literal>client_connection</literal>+        trigger when a client connects. This parameter is switched on by default.+        Errors in trigger code can prevent user to login to the system.+        I this case disabling this parameter in connection string can solve the problem:+        <literal>psql \"dbname=postgres options='-c enable_client_connection_trigger=false'\"</literal>.+       </para>+      </listitem>+     </varlistentry>There should be note, so only superuser can change this valueThere is should be tab-complete supportdiff --git a/src/bin/psql/tab-complete.c b/src/bin/psql/tab-complete.cindex 3a43c09bf6..08f00d8fc4 100644--- a/src/bin/psql/tab-complete.c+++ b/src/bin/psql/tab-complete.c@@ -2970,7 +2970,8 @@ psql_completion(const char *text, int start, int end)        COMPLETE_WITH(\"ON\");    /* Complete CREATE EVENT TRIGGER <name> ON with event_type */    else if (Matches(\"CREATE\", \"EVENT\", \"TRIGGER\", MatchAny, \"ON\"))-       COMPLETE_WITH(\"ddl_command_start\", \"ddl_command_end\", \"sql_drop\");+       COMPLETE_WITH(\"ddl_command_start\", \"ddl_command_end\",+                     \"client_connection\", \"sql_drop\");     /*     * Complete CREATE EVENT TRIGGER <name> ON <event_type>.  EXECUTE FUNCTIONRegardsPavel\n\n\n\n\n-- \n\n\nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Tue, 22 Dec 2020 19:19:51 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 22.12.2020 21:19, Pavel Stehule wrote:\n>\n>\n> út 22. 12. 2020 v 12:42 odesílatel Konstantin Knizhnik \n> <k.knizhnik@postgrespro.ru <mailto:k.knizhnik@postgrespro.ru>> napsal:\n>\n>\n>\n> On 22.12.2020 12:25, Pavel Stehule wrote:\n>>\n>> regress tests fails\n>>\n>>      sysviews                     ... FAILED    112 ms\n>> test event_trigger                ... FAILED (test process exited\n>> with exit code 2)      447 ms\n>> test fast_default                 ... FAILED  392 ms\n>> test stats                        ... FAILED  626 ms\n>> ============== shutting down postmaster     ==============\n>>\n>\n> Sorry, fixed.\n>\n>\n> no problem\n>\n> I had to fix doc\n>\n> diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml\n> index 6ff783273f..7aded1848f 100644\n> --- a/doc/src/sgml/config.sgml\n> +++ b/doc/src/sgml/config.sgml\n> @@ -1008,7 +1008,7 @@ include_dir 'conf.d'\n>          trigger when a client connects. This parameter is switched on \n> by default.\n>          Errors in trigger code can prevent user to login to the system.\n>          I this case disabling this parameter in connection string can \n> solve the problem:\n> -        <literal>psql \"dbname=postgres options='-c \n> enable_client_connection_trigger=false'\".\n> +        <literal>psql \"dbname=postgres options='-c \n> enable_client_connection_trigger=false'\"</literal>.\n>         </para>\n>        </listitem>\n>       </varlistentry>\n>\n> I am thinking again about enable_client_connection_trigger, and \n> although it can look useless (because error is ignored for superuser), \n> it can be useful for some debugging and administration purposes. \n> Probably we don't want to start the client_connection trigger from \n> backup tools, maybe from some monitoring tools. Maybe the possibility \n> to set this GUC can be dedicated to some special role (like \n> pg_signal_backend).\n>\n> +     <varlistentry id=\"guc-enable-client-connection-trigger\" \n> xreflabel=\"enable_client_connection_trigger\">\n> +  <term><varname>enable_client_connection_trigger</varname> \n> (<type>boolean</type>)\n> +      <indexterm>\n> + <primary><varname>enable_client_connection_trigger</varname> \n> configuration parameter</primary>\n> +      </indexterm>\n> +      </term>\n> +      <listitem>\n> +       <para>\n> +        Enables firing the <literal>client_connection</literal>\n> +        trigger when a client connects. This parameter is switched on \n> by default.\n> +        Errors in trigger code can prevent user to login to the system.\n> +        I this case disabling this parameter in connection string can \n> solve the problem:\n> +        <literal>psql \"dbname=postgres options='-c \n> enable_client_connection_trigger=false'\"</literal>.\n> +       </para>\n> +      </listitem>\n> +     </varlistentry>\n>\n> There should be note, so only superuser can change this value\n>\n> There is should be tab-complete support\n>\n> diff --git a/src/bin/psql/tab-complete.c b/src/bin/psql/tab-complete.c\n> index 3a43c09bf6..08f00d8fc4 100644\n> --- a/src/bin/psql/tab-complete.c\n> +++ b/src/bin/psql/tab-complete.c\n> @@ -2970,7 +2970,8 @@ psql_completion(const char *text, int start, int \n> end)\n>         COMPLETE_WITH(\"ON\");\n>     /* Complete CREATE EVENT TRIGGER <name> ON with event_type */\n>     else if (Matches(\"CREATE\", \"EVENT\", \"TRIGGER\", MatchAny, \"ON\"))\n> -       COMPLETE_WITH(\"ddl_command_start\", \"ddl_command_end\", \"sql_drop\");\n> +       COMPLETE_WITH(\"ddl_command_start\", \"ddl_command_end\",\n> +                     \"client_connection\", \"sql_drop\");\n>\n>     /*\n>      * Complete CREATE EVENT TRIGGER <name> ON <event_type>.  EXECUTE \n> FUNCTION\n\nThank you.\nI have applied all your fixes in on_connect_event_trigger-12.patch.\n\nConcerning enable_client_connection_trigger GUC, I think that it is \nreally useful: it is the fastest and simplest way to disable login \ntriggers in case\nof some problems with them (not only for superuser itself, but for all \nusers). Yes, it can be also done using \"ALTER EVENT TRIGGER DISABLE\".\nBut assume that you have a lot of databases with different login \npolicies enforced by on-login event triggers. And you want temporary \ndisable them all, for example for testing purposes.\nIn this case GUC is most convenient way to do it.\n\n\n\nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Thu, 24 Dec 2020 13:00:05 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi\n\n\nThank you.\n> I have applied all your fixes in on_connect_event_trigger-12.patch.\n>\n> Concerning enable_client_connection_trigger GUC, I think that it is really\n> useful: it is the fastest and simplest way to disable login triggers in case\n> of some problems with them (not only for superuser itself, but for all\n> users). Yes, it can be also done using \"ALTER EVENT TRIGGER DISABLE\".\n> But assume that you have a lot of databases with different login policies\n> enforced by on-login event triggers. And you want temporary disable them\n> all, for example for testing purposes.\n> In this case GUC is most convenient way to do it.\n>\n>\nThere was typo in patch\n\ndiff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml\nindex f810789..8861f1b 100644\n--- a/doc/src/sgml/config.sgml\n+++ b/doc/src/sgml/config.sgml\n@@ -1,4 +1,4 @@\n-<!-- doc/src/sgml/config.sgml -->\n+\\<!-- doc/src/sgml/config.sgml -->\n\nI have not any objections against functionality or design. I tested the\nperformance, and there are no negative impacts when this feature is not\nused. There is significant overhead related to plpgsql runtime\ninitialization, but when this trigger will be used, then probably some\nother PLpgSQL procedures and functions will be used too, and then this\noverhead can be ignored.\n\n* make without warnings\n* make check-world passed\n* doc build passed\n\nPossible ToDo:\n\nThe documentation can contain a note so usage connect triggers in\nenvironments with short life sessions and very short fast queries without\nusage PLpgSQL functions or procedures can have negative impact on\nperformance due overhead of initialization of PLpgSQL engine.\n\nI'll mark this patch as ready for committers\n\nRegards\n\nPavel\n\n\n\n>\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>", "msg_date": "Sat, 26 Dec 2020 08:00:01 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "so 26. 12. 2020 v 8:00 odesílatel Pavel Stehule <pavel.stehule@gmail.com>\nnapsal:\n\n> Hi\n>\n>\n> Thank you.\n>> I have applied all your fixes in on_connect_event_trigger-12.patch.\n>>\n>> Concerning enable_client_connection_trigger GUC, I think that it is\n>> really useful: it is the fastest and simplest way to disable login triggers\n>> in case\n>> of some problems with them (not only for superuser itself, but for all\n>> users). Yes, it can be also done using \"ALTER EVENT TRIGGER DISABLE\".\n>> But assume that you have a lot of databases with different login policies\n>> enforced by on-login event triggers. And you want temporary disable them\n>> all, for example for testing purposes.\n>> In this case GUC is most convenient way to do it.\n>>\n>>\n> There was typo in patch\n>\n> diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml\n> index f810789..8861f1b 100644\n> --- a/doc/src/sgml/config.sgml\n> +++ b/doc/src/sgml/config.sgml\n> @@ -1,4 +1,4 @@\n> -<!-- doc/src/sgml/config.sgml -->\n> +\\<!-- doc/src/sgml/config.sgml -->\n>\n> I have not any objections against functionality or design. I tested the\n> performance, and there are no negative impacts when this feature is not\n> used. There is significant overhead related to plpgsql runtime\n> initialization, but when this trigger will be used, then probably some\n> other PLpgSQL procedures and functions will be used too, and then this\n> overhead can be ignored.\n>\n> * make without warnings\n> * make check-world passed\n> * doc build passed\n>\n> Possible ToDo:\n>\n> The documentation can contain a note so usage connect triggers in\n> environments with short life sessions and very short fast queries without\n> usage PLpgSQL functions or procedures can have negative impact on\n> performance due overhead of initialization of PLpgSQL engine.\n>\n> I'll mark this patch as ready for committers\n>\n\nlooks so this patch has not entry in commitfestapp 2021-01\n\nRegards\n\nPavel\n\n\n> Regards\n>\n> Pavel\n>\n>\n>\n>>\n>> Konstantin Knizhnik\n>> Postgres Professional: http://www.postgrespro.com\n>> The Russian Postgres Company\n>>\n>>\n\nso 26. 12. 2020 v 8:00 odesílatel Pavel Stehule <pavel.stehule@gmail.com> napsal:Hi\n Thank you.\n I have applied all your fixes in on_connect_event_trigger-12.patch.\n\n Concerning enable_client_connection_trigger GUC, I think that it is\n really useful: it is the fastest and simplest way to disable login\n triggers in case\n of some problems with them (not only for superuser itself, but for\n all users). Yes, it can be also done using \"ALTER EVENT TRIGGER\n DISABLE\".\n But assume that you have a lot of databases with different login\n policies enforced by on-login event triggers. And you want temporary\n disable them all, for example for testing purposes.\n In this case GUC is most convenient way to do it.\nThere was typo in patch diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgmlindex f810789..8861f1b 100644--- a/doc/src/sgml/config.sgml+++ b/doc/src/sgml/config.sgml@@ -1,4 +1,4 @@-<!-- doc/src/sgml/config.sgml -->+\\<!-- doc/src/sgml/config.sgml --> I have not any objections against functionality or design. I tested the performance, and there are no negative impacts when this feature is not used. There is significant overhead related to plpgsql runtime initialization, but when this trigger will be used, then probably some other PLpgSQL procedures and functions will be used too, and then this overhead can be ignored.* make without warnings* make check-world passed* doc build passedPossible ToDo:The documentation can contain a note so usage connect triggers in environments with short life sessions and very short fast queries without usage PLpgSQL functions or procedures can have negative impact on performance due overhead of initialization of PLpgSQL engine.I'll mark this patch as ready for committers looks so this patch has not entry in commitfestapp 2021-01RegardsPavelRegardsPavel\n\n\nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Sat, 26 Dec 2020 08:03:16 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Sat, Dec 26, 2020 at 4:04 PM Pavel Stehule <pavel.stehule@gmail.com> wrote:\n>\n>\n>\n> so 26. 12. 2020 v 8:00 odesílatel Pavel Stehule <pavel.stehule@gmail.com> napsal:\n>>\n>> Hi\n>>\n>>\n>>> Thank you.\n>>> I have applied all your fixes in on_connect_event_trigger-12.patch.\n>>>\n>>> Concerning enable_client_connection_trigger GUC, I think that it is really useful: it is the fastest and simplest way to disable login triggers in case\n>>> of some problems with them (not only for superuser itself, but for all users). Yes, it can be also done using \"ALTER EVENT TRIGGER DISABLE\".\n>>> But assume that you have a lot of databases with different login policies enforced by on-login event triggers. And you want temporary disable them all, for example for testing purposes.\n>>> In this case GUC is most convenient way to do it.\n>>>\n>>\n>> There was typo in patch\n>>\n>> diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml\n>> index f810789..8861f1b 100644\n>> --- a/doc/src/sgml/config.sgml\n>> +++ b/doc/src/sgml/config.sgml\n>> @@ -1,4 +1,4 @@\n>> -<!-- doc/src/sgml/config.sgml -->\n>> +\\<!-- doc/src/sgml/config.sgml -->\n>>\n>> I have not any objections against functionality or design. I tested the performance, and there are no negative impacts when this feature is not used. There is significant overhead related to plpgsql runtime initialization, but when this trigger will be used, then probably some other PLpgSQL procedures and functions will be used too, and then this overhead can be ignored.\n>>\n>> * make without warnings\n>> * make check-world passed\n>> * doc build passed\n>>\n>> Possible ToDo:\n>>\n>> The documentation can contain a note so usage connect triggers in environments with short life sessions and very short fast queries without usage PLpgSQL functions or procedures can have negative impact on performance due overhead of initialization of PLpgSQL engine.\n>>\n>> I'll mark this patch as ready for committers\n>\n>\n> looks so this patch has not entry in commitfestapp 2021-01\n>\n\nYeah, please register this patch before the next CommitFest[1] starts,\n2021-01-01 AoE[2].\n\nRegards,\n\n[1] https://commitfest.postgresql.org/31/\n[2] https://en.wikipedia.org/wiki/Anywhere_on_Earth\n\n-- \nMasahiko Sawada\nEnterpriseDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Mon, 28 Dec 2020 21:15:52 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Mon, Dec 28, 2020 at 5:46 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> On Sat, Dec 26, 2020 at 4:04 PM Pavel Stehule <pavel.stehule@gmail.com> wrote:\n> >\n> >\n> >\n> > so 26. 12. 2020 v 8:00 odesílatel Pavel Stehule <pavel.stehule@gmail.com> napsal:\n> >>\n> >> Hi\n> >>\n> >>\n> >>> Thank you.\n> >>> I have applied all your fixes in on_connect_event_trigger-12.patch.\n> >>>\n> >>> Concerning enable_client_connection_trigger GUC, I think that it is really useful: it is the fastest and simplest way to disable login triggers in case\n> >>> of some problems with them (not only for superuser itself, but for all users). Yes, it can be also done using \"ALTER EVENT TRIGGER DISABLE\".\n> >>> But assume that you have a lot of databases with different login policies enforced by on-login event triggers. And you want temporary disable them all, for example for testing purposes.\n> >>> In this case GUC is most convenient way to do it.\n> >>>\n> >>\n> >> There was typo in patch\n> >>\n> >> diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml\n> >> index f810789..8861f1b 100644\n> >> --- a/doc/src/sgml/config.sgml\n> >> +++ b/doc/src/sgml/config.sgml\n> >> @@ -1,4 +1,4 @@\n> >> -<!-- doc/src/sgml/config.sgml -->\n> >> +\\<!-- doc/src/sgml/config.sgml -->\n> >>\n> >> I have not any objections against functionality or design. I tested the performance, and there are no negative impacts when this feature is not used. There is significant overhead related to plpgsql runtime initialization, but when this trigger will be used, then probably some other PLpgSQL procedures and functions will be used too, and then this overhead can be ignored.\n> >>\n> >> * make without warnings\n> >> * make check-world passed\n> >> * doc build passed\n> >>\n> >> Possible ToDo:\n> >>\n> >> The documentation can contain a note so usage connect triggers in environments with short life sessions and very short fast queries without usage PLpgSQL functions or procedures can have negative impact on performance due overhead of initialization of PLpgSQL engine.\n> >>\n> >> I'll mark this patch as ready for committers\n> >\n> >\n> > looks so this patch has not entry in commitfestapp 2021-01\n> >\n>\n> Yeah, please register this patch before the next CommitFest[1] starts,\n> 2021-01-01 AoE[2].\n>\n\nKonstantin, did you register this patch in any CF? Even though the\nreviewer seems to be happy with the patch, I am afraid that we might\nlose track of this unless we register it.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Thu, 28 Jan 2021 08:17:07 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Thu, Jan 28, 2021 at 8:17 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Mon, Dec 28, 2020 at 5:46 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n> > On Sat, Dec 26, 2020 at 4:04 PM Pavel Stehule <pavel.stehule@gmail.com> wrote:\n> > >\n> > >\n> > >\n> > > so 26. 12. 2020 v 8:00 odesílatel Pavel Stehule <pavel.stehule@gmail.com> napsal:\n> > >>\n> > >> Hi\n> > >>\n> > >>\n> > >>> Thank you.\n> > >>> I have applied all your fixes in on_connect_event_trigger-12.patch.\n> > >>>\n> > >>> Concerning enable_client_connection_trigger GUC, I think that it is really useful: it is the fastest and simplest way to disable login triggers in case\n> > >>> of some problems with them (not only for superuser itself, but for all users). Yes, it can be also done using \"ALTER EVENT TRIGGER DISABLE\".\n> > >>> But assume that you have a lot of databases with different login policies enforced by on-login event triggers. And you want temporary disable them all, for example for testing purposes.\n> > >>> In this case GUC is most convenient way to do it.\n> > >>>\n> > >>\n> > >> There was typo in patch\n> > >>\n> > >> diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml\n> > >> index f810789..8861f1b 100644\n> > >> --- a/doc/src/sgml/config.sgml\n> > >> +++ b/doc/src/sgml/config.sgml\n> > >> @@ -1,4 +1,4 @@\n> > >> -<!-- doc/src/sgml/config.sgml -->\n> > >> +\\<!-- doc/src/sgml/config.sgml -->\n> > >>\n> > >> I have not any objections against functionality or design. I tested the performance, and there are no negative impacts when this feature is not used. There is significant overhead related to plpgsql runtime initialization, but when this trigger will be used, then probably some other PLpgSQL procedures and functions will be used too, and then this overhead can be ignored.\n> > >>\n> > >> * make without warnings\n> > >> * make check-world passed\n> > >> * doc build passed\n> > >>\n> > >> Possible ToDo:\n> > >>\n> > >> The documentation can contain a note so usage connect triggers in environments with short life sessions and very short fast queries without usage PLpgSQL functions or procedures can have negative impact on performance due overhead of initialization of PLpgSQL engine.\n> > >>\n> > >> I'll mark this patch as ready for committers\n> > >\n> > >\n> > > looks so this patch has not entry in commitfestapp 2021-01\n> > >\n> >\n> > Yeah, please register this patch before the next CommitFest[1] starts,\n> > 2021-01-01 AoE[2].\n> >\n>\n> Konstantin, did you register this patch in any CF? Even though the\n> reviewer seems to be happy with the patch, I am afraid that we might\n> lose track of this unless we register it.\n>\n\nI see the CF entry (https://commitfest.postgresql.org/31/2900/) for\nthis work. Sorry for the noise.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Thu, 28 Jan 2021 10:24:24 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "\n\nOn 28.01.2021 5:47, Amit Kapila wrote:\n> On Mon, Dec 28, 2020 at 5:46 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>> On Sat, Dec 26, 2020 at 4:04 PM Pavel Stehule <pavel.stehule@gmail.com> wrote:\n>>>\n>>>\n>>> so 26. 12. 2020 v 8:00 odesílatel Pavel Stehule <pavel.stehule@gmail.com> napsal:\n>>>> Hi\n>>>>\n>>>>\n>>>>> Thank you.\n>>>>> I have applied all your fixes in on_connect_event_trigger-12.patch.\n>>>>>\n>>>>> Concerning enable_client_connection_trigger GUC, I think that it is really useful: it is the fastest and simplest way to disable login triggers in case\n>>>>> of some problems with them (not only for superuser itself, but for all users). Yes, it can be also done using \"ALTER EVENT TRIGGER DISABLE\".\n>>>>> But assume that you have a lot of databases with different login policies enforced by on-login event triggers. And you want temporary disable them all, for example for testing purposes.\n>>>>> In this case GUC is most convenient way to do it.\n>>>>>\n>>>> There was typo in patch\n>>>>\n>>>> diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml\n>>>> index f810789..8861f1b 100644\n>>>> --- a/doc/src/sgml/config.sgml\n>>>> +++ b/doc/src/sgml/config.sgml\n>>>> @@ -1,4 +1,4 @@\n>>>> -<!-- doc/src/sgml/config.sgml -->\n>>>> +\\<!-- doc/src/sgml/config.sgml -->\n>>>>\n>>>> I have not any objections against functionality or design. I tested the performance, and there are no negative impacts when this feature is not used. There is significant overhead related to plpgsql runtime initialization, but when this trigger will be used, then probably some other PLpgSQL procedures and functions will be used too, and then this overhead can be ignored.\n>>>>\n>>>> * make without warnings\n>>>> * make check-world passed\n>>>> * doc build passed\n>>>>\n>>>> Possible ToDo:\n>>>>\n>>>> The documentation can contain a note so usage connect triggers in environments with short life sessions and very short fast queries without usage PLpgSQL functions or procedures can have negative impact on performance due overhead of initialization of PLpgSQL engine.\n>>>>\n>>>> I'll mark this patch as ready for committers\n>>>\n>>> looks so this patch has not entry in commitfestapp 2021-01\n>>>\n>> Yeah, please register this patch before the next CommitFest[1] starts,\n>> 2021-01-01 AoE[2].\n>>\n> Konstantin, did you register this patch in any CF? Even though the\n> reviewer seems to be happy with the patch, I am afraid that we might\n> lose track of this unless we register it.\n>\nYes, certainly:\nhttps://commitfest.postgresql.org/31/2900/\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Thu, 28 Jan 2021 12:04:28 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi,\n\nThank you, Konstantin, for this very good feature with numerous use cases.\nPlease find the modified patch attached.\n\nI’ve added the ‘enable_client_connection_trigger’ GUC to the sample config file and also an additional example page to the docs.\nCheck world has passed and it is ready for committer.\n  \n>Четверг, 28 января 2021, 12:04 +03:00 от Konstantin Knizhnik <k.knizhnik@postgrespro.ru>:\n> \n>\n>\n>On 28.01.2021 5:47, Amit Kapila wrote:\n>> On Mon, Dec 28, 2020 at 5:46 PM Masahiko Sawada < sawada.mshk@gmail.com > wrote:\n>>> On Sat, Dec 26, 2020 at 4:04 PM Pavel Stehule < pavel.stehule@gmail.com > wrote:\n>>>>\n>>>>\n>>>> so 26. 12. 2020 v 8:00 odesílatel Pavel Stehule < pavel.stehule@gmail.com > napsal:\n>>>>> Hi\n>>>>>\n>>>>>\n>>>>>> Thank you.\n>>>>>> I have applied all your fixes in on_connect_event_trigger-12.patch.\n>>>>>>\n>>>>>> Concerning enable_client_connection_trigger GUC, I think that it is really useful: it is the fastest and simplest way to disable login triggers in case\n>>>>>> of some problems with them (not only for superuser itself, but for all users). Yes, it can be also done using \"ALTER EVENT TRIGGER DISABLE\".\n>>>>>> But assume that you have a lot of databases with different login policies enforced by on-login event triggers. And you want temporary disable them all, for example for testing purposes.\n>>>>>> In this case GUC is most convenient way to do it.\n>>>>>>\n>>>>> There was typo in patch\n>>>>>\n>>>>> diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml\n>>>>> index f810789..8861f1b 100644\n>>>>> --- a/doc/src/sgml/config.sgml\n>>>>> +++ b/doc/src/sgml/config.sgml\n>>>>> @@ -1,4 +1,4 @@\n>>>>> -<!-- doc/src/sgml/config.sgml -->\n>>>>> +\\<!-- doc/src/sgml/config.sgml -->\n>>>>>\n>>>>> I have not any objections against functionality or design. I tested the performance, and there are no negative impacts when this feature is not used. There is significant overhead related to plpgsql runtime initialization, but when this trigger will be used, then probably some other PLpgSQL procedures and functions will be used too, and then this overhead can be ignored.\n>>>>>\n>>>>> * make without warnings\n>>>>> * make check-world passed\n>>>>> * doc build passed\n>>>>>\n>>>>> Possible ToDo:\n>>>>>\n>>>>> The documentation can contain a note so usage connect triggers in environments with short life sessions and very short fast queries without usage PLpgSQL functions or procedures can have negative impact on performance due overhead of initialization of PLpgSQL engine.\n>>>>>\n>>>>> I'll mark this patch as ready for committers\n>>>>\n>>>> looks so this patch has not entry in commitfestapp 2021-01\n>>>>\n>>> Yeah, please register this patch before the next CommitFest[1] starts,\n>>> 2021-01-01 AoE[2].\n>>>\n>> Konstantin, did you register this patch in any CF? Even though the\n>> reviewer seems to be happy with the patch, I am afraid that we might\n>> lose track of this unless we register it.\n>> Yes, certainly:\n>https://commitfest.postgresql.org/31/2900/\n>\n>--\n>Konstantin Knizhnik\n>Postgres Professional: http://www.postgrespro.com\n>The Russian Postgres Company\n>\n>", "msg_date": "Tue, 16 Mar 2021 14:32:31 +0300", "msg_from": "=?UTF-8?B?SXZhbiBQYW5jaGVua28=?= <wao@mail.ru>", "msg_from_op": false, "msg_subject": "=?UTF-8?B?UmVbMl06IE9uIGxvZ2luIHRyaWdnZXI6IHRha2UgdGhyZWU=?=" }, { "msg_contents": "Hi,\nI have upgraded the patch for the 14th version.\n>Вторник, 16 марта 2021, 14:32 +03:00 от Ivan Panchenko <wao@mail.ru>:\n> \n>Hi,\n>\n>Thank you, Konstantin, for this very good feature with numerous use cases.\n>Please find the modified patch attached.\n>\n>I’ve added the ‘enable_client_connection_trigger’ GUC to the sample config file and also an additional example page to the docs.\n>Check world has passed and it is ready for committer.\n> \n>>Четверг, 28 января 2021, 12:04 +03:00 от Konstantin Knizhnik < k.knizhnik@postgrespro.ru >:\n>> \n>>\n>>\n>>On 28.01.2021 5:47, Amit Kapila wrote:\n>>> On Mon, Dec 28, 2020 at 5:46 PM Masahiko Sawada < sawada.mshk@gmail.com > wrote:\n>>>> On Sat, Dec 26, 2020 at 4:04 PM Pavel Stehule < pavel.stehule@gmail.com > wrote:\n>>>>>\n>>>>>\n>>>>> so 26. 12. 2020 v 8:00 odesílatel Pavel Stehule < pavel.stehule@gmail.com > napsal:\n>>>>>> Hi\n>>>>>>\n>>>>>>\n>>>>>>> Thank you.\n>>>>>>> I have applied all your fixes in on_connect_event_trigger-12.patch.\n>>>>>>>\n>>>>>>> Concerning enable_client_connection_trigger GUC, I think that it is really useful: it is the fastest and simplest way to disable login triggers in case\n>>>>>>> of some problems with them (not only for superuser itself, but for all users). Yes, it can be also done using \"ALTER EVENT TRIGGER DISABLE\".\n>>>>>>> But assume that you have a lot of databases with different login policies enforced by on-login event triggers. And you want temporary disable them all, for example for testing purposes.\n>>>>>>> In this case GUC is most convenient way to do it.\n>>>>>>>\n>>>>>> There was typo in patch\n>>>>>>\n>>>>>> diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml\n>>>>>> index f810789..8861f1b 100644\n>>>>>> --- a/doc/src/sgml/config.sgml\n>>>>>> +++ b/doc/src/sgml/config.sgml\n>>>>>> @@ -1,4 +1,4 @@\n>>>>>> -<!-- doc/src/sgml/config.sgml -->\n>>>>>> +\\<!-- doc/src/sgml/config.sgml -->\n>>>>>>\n>>>>>> I have not any objections against functionality or design. I tested the performance, and there are no negative impacts when this feature is not used. There is significant overhead related to plpgsql runtime initialization, but when this trigger will be used, then probably some other PLpgSQL procedures and functions will be used too, and then this overhead can be ignored.\n>>>>>>\n>>>>>> * make without warnings\n>>>>>> * make check-world passed\n>>>>>> * doc build passed\n>>>>>>\n>>>>>> Possible ToDo:\n>>>>>>\n>>>>>> The documentation can contain a note so usage connect triggers in environments with short life sessions and very short fast queries without usage PLpgSQL functions or procedures can have negative impact on performance due overhead of initialization of PLpgSQL engine.\n>>>>>>\n>>>>>> I'll mark this patch as ready for committers\n>>>>>\n>>>>> looks so this patch has not entry in commitfestapp 2021-01\n>>>>>\n>>>> Yeah, please register this patch before the next CommitFest[1] starts,\n>>>> 2021-01-01 AoE[2].\n>>>>\n>>> Konstantin, did you register this patch in any CF? Even though the\n>>> reviewer seems to be happy with the patch, I am afraid that we might\n>>> lose track of this unless we register it.\n>>> Yes, certainly:\n>>https://commitfest.postgresql.org/31/2900/\n>>\n>>--\n>>Konstantin Knizhnik\n>>Postgres Professional: http://www.postgrespro.com\n>>The Russian Postgres Company\n>>\n>>  \n> \n> \n> \n>", "msg_date": "Thu, 20 May 2021 07:44:58 +0300", "msg_from": "=?UTF-8?B?SXZhbiBQYW5jaGVua28=?= <wao@mail.ru>", "msg_from_op": false, "msg_subject": "=?UTF-8?B?UmVbM106IE9uIGxvZ2luIHRyaWdnZXI6IHRha2UgdGhyZWU=?=" }, { "msg_contents": "On Thu, May 20, 2021 at 2:45 PM Ivan Panchenko <wao@mail.ru> wrote:\n>\n> I have upgraded the patch for the 14th version.\n>\n\nI have some feedback on the patch:\n\n(1) The patch adds 3 whitespace errors (\"git apply <patch-file>\"\nreports 3 warnings)\n\n\n(2) doc/src/sgml/catalogs.sgml\n\nCURRENTLY:\nThis flag is used to avoid extra lookup of pg_event_trigger table on\neach backend startup.\n\nSUGGEST:\nThis flag is used to avoid extra lookups on the pg_event_trigger table\nduring each backend startup.\n\n\n(3) doc/src/sgml/config.sgml\n\nCURRENTLY:\nErrors in trigger code can prevent user to login to the system.In this\ncase disabling this parameter in connection string can solve the\nproblem:\n\nSUGGEST:\nErrors in the trigger code can prevent a user from logging in to the\nsystem. In this case, the parameter can be disabled in the connection\nstring, to allow the user to login:\n\n\n(4) doc/src/sgml/event-trigger.sgml\n\n(i)\n\nCURRENTLY:\nAn event trigger fires whenever the event with which it is associated\noccurs in the database in which it is defined. Currently, the only\n\nSUGGEST:\nAn event trigger fires whenever an associated event occurs in the\ndatabase in which it is defined. Currently, the only\n\n\n(ii)\n\nCURRENTLY:\ncan be useful for client connections logging,\n\nSUGGEST:\ncan be useful for logging client connections,\n\n\n(5) src/backend/commands/event_trigger.c\n\n(i) There are two instances of code blocks like:\n\n xxxx = table_open(...);\n tuple = SearchSysCacheCopy1(...);\n table_close(...);\n\nThese should end with: \"heap_freetuple(tuple);\"\n\n(ii) Typo \"nuder\" and grammar:\n\nCURRENTLY:\nThere can be race condition: event trigger may be added after we have\nscanned pg_event_trigger table. Repeat this test nuder pg_database\ntable lock.\n\nSUGGEST:\nThere can be a race condition: the event trigger may be added after we\nhave scanned the pg_event_trigger table. Repeat this test under the\npg_database table lock.\n\n\n(6) src/backend/utils/misc/postgresql.conf.sample\n\nCURRENTLY:\n+#enable_client_connection_trigger = true # enables firing the\nclient_connection trigger when a client connect\n\nSUGGEST:\n+#enable_client_connection_trigger = true # enables firing the\nclient_connection trigger when a client connects\n\n\nRegards,\nGreg Nancarrow\nFujitsu Australia\n\n\n", "msg_date": "Fri, 21 May 2021 14:46:11 +1000", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Re[3]: On login trigger: take three" }, { "msg_contents": "On Fri, May 21, 2021 at 2:46 PM Greg Nancarrow <gregn4422@gmail.com> wrote:\n>\n> On Thu, May 20, 2021 at 2:45 PM Ivan Panchenko <wao@mail.ru> wrote:\n> >\n> > I have upgraded the patch for the 14th version.\n> >\n>\n> I have some feedback on the patch:\n>\n\nI've attached an updated version of the patch.\nI've applied my review comments and done a bit more tidying up of\ndocumentation and comments.\nAlso, I found that the previously-posted patch was broken by\nsnapshot-handling changes in commit 84f5c290 (with patch applied,\nresulting in a coredump during regression tests) so I've added a fix\nfor that too.\n\nRegards,\nGreg Nancarrow\nFujitsu Australia", "msg_date": "Thu, 3 Jun 2021 13:05:50 +1000", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Re[3]: On login trigger: take three" }, { "msg_contents": "On Thu, Jun 3, 2021 at 8:36 AM Greg Nancarrow <gregn4422@gmail.com> wrote:\n>\n> On Fri, May 21, 2021 at 2:46 PM Greg Nancarrow <gregn4422@gmail.com> wrote:\n> >\n> > On Thu, May 20, 2021 at 2:45 PM Ivan Panchenko <wao@mail.ru> wrote:\n> > >\n> > > I have upgraded the patch for the 14th version.\n> > >\n> >\n> > I have some feedback on the patch:\n> >\n>\n> I've attached an updated version of the patch.\n> I've applied my review comments and done a bit more tidying up of\n> documentation and comments.\n> Also, I found that the previously-posted patch was broken by\n> snapshot-handling changes in commit 84f5c290 (with patch applied,\n> resulting in a coredump during regression tests) so I've added a fix\n> for that too.\n\nCFBot shows the following failure:\n# poll_query_until timed out executing this query:\n# SELECT '0/3046250' <= replay_lsn AND state = 'streaming' FROM\npg_catalog.pg_stat_replication WHERE application_name = 'standby_1';\n# expecting this output:\n# t\n# last actual query output:\n# t\n# with stderr:\n# NOTICE: You are welcome!\n# Looks like your test exited with 29 before it could output anything.\nt/001_stream_rep.pl ..................\nDubious, test returned 29 (wstat 7424, 0x1d00)\n\nRegards,\nVignesh\n\n\n", "msg_date": "Sun, 4 Jul 2021 08:50:59 +0530", "msg_from": "vignesh C <vignesh21@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Re[3]: On login trigger: take three" }, { "msg_contents": "On Sun, Jul 4, 2021 at 1:21 PM vignesh C <vignesh21@gmail.com> wrote:\n>\n> CFBot shows the following failure:\n> # poll_query_until timed out executing this query:\n> # SELECT '0/3046250' <= replay_lsn AND state = 'streaming' FROM\n> pg_catalog.pg_stat_replication WHERE application_name = 'standby_1';\n> # expecting this output:\n> # t\n> # last actual query output:\n> # t\n> # with stderr:\n> # NOTICE: You are welcome!\n> # Looks like your test exited with 29 before it could output anything.\n> t/001_stream_rep.pl ..................\n> Dubious, test returned 29 (wstat 7424, 0x1d00)\n>\n\nThanks.\nI found that the patch was broken by commit f452aaf7d (the part\n\"adjust poll_query_until to insist on empty stderr as well as a stdout\nmatch\").\nSo I had to remove a \"RAISE NOTICE\" (which was just an informational\nmessage) from the login trigger function, to satisfy the new\npoll_query_until expectations.\nAlso, I updated a PG14 version check (now must check PG15 version).\n\nRegards,\nGreg Nancarrow\nFujitsu Australia", "msg_date": "Wed, 7 Jul 2021 10:55:16 +1000", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Re[3]: On login trigger: take three" }, { "msg_contents": "On Wed, Jul 7, 2021 at 5:55 AM Greg Nancarrow <gregn4422@gmail.com> wrote:\n\n> On Sun, Jul 4, 2021 at 1:21 PM vignesh C <vignesh21@gmail.com> wrote:\n> >\n> > CFBot shows the following failure:\n> > # poll_query_until timed out executing this query:\n> > # SELECT '0/3046250' <= replay_lsn AND state = 'streaming' FROM\n> > pg_catalog.pg_stat_replication WHERE application_name = 'standby_1';\n> > # expecting this output:\n> > # t\n> > # last actual query output:\n> > # t\n> > # with stderr:\n> > # NOTICE: You are welcome!\n> > # Looks like your test exited with 29 before it could output anything.\n> > t/001_stream_rep.pl ..................\n> > Dubious, test returned 29 (wstat 7424, 0x1d00)\n> >\n>\n> Thanks.\n> I found that the patch was broken by commit f452aaf7d (the part\n> \"adjust poll_query_until to insist on empty stderr as well as a stdout\n> match\").\n> So I had to remove a \"RAISE NOTICE\" (which was just an informational\n> message) from the login trigger function, to satisfy the new\n> poll_query_until expectations.\n> Also, I updated a PG14 version check (now must check PG15 version).\n>\n> Regards,\n> Greg Nancarrow\n> Fujitsu Australia\n>\n\n\nThe patch does not apply, and rebase is required.\n\nHunk #1 FAILED at 93.\n1 out of 1 hunk FAILED -- saving rejects to file\nsrc/test/regress/expected/sysviews.out.rej\n\n\nI am not changing the status because it is a minor change and the\npatch is already \"Ready for Committer\".\n\n\n-- \nIbrar Ahmed\n\nOn Wed, Jul 7, 2021 at 5:55 AM Greg Nancarrow <gregn4422@gmail.com> wrote:On Sun, Jul 4, 2021 at 1:21 PM vignesh C <vignesh21@gmail.com> wrote:\n>\n> CFBot shows the following failure:\n> # poll_query_until timed out executing this query:\n> # SELECT '0/3046250' <= replay_lsn AND state = 'streaming' FROM\n> pg_catalog.pg_stat_replication WHERE application_name = 'standby_1';\n> # expecting this output:\n> # t\n> # last actual query output:\n> # t\n> # with stderr:\n> # NOTICE: You are welcome!\n> # Looks like your test exited with 29 before it could output anything.\n> t/001_stream_rep.pl ..................\n> Dubious, test returned 29 (wstat 7424, 0x1d00)\n>\n\nThanks.\nI found that the patch was broken by commit f452aaf7d (the part\n\"adjust poll_query_until to insist on empty stderr as well as a stdout\nmatch\").\nSo I had to remove a \"RAISE NOTICE\" (which was just an informational\nmessage) from the login trigger function, to satisfy the new\npoll_query_until expectations.\nAlso, I updated a PG14 version check (now must check PG15 version).\n\nRegards,\nGreg Nancarrow\nFujitsu Australia\nThe patch does not apply, and rebase is required. Hunk #1 FAILED at 93.\n1 out of 1 hunk FAILED -- saving rejects to file src/test/regress/expected/sysviews.out.rejI am not changing the status because it is a minor change and the patch is already \"Ready for Committer\".-- Ibrar Ahmed", "msg_date": "Mon, 19 Jul 2021 15:17:43 +0500", "msg_from": "Ibrar Ahmed <ibrar.ahmad@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Re[3]: On login trigger: take three" }, { "msg_contents": "On Mon, Jul 19, 2021 at 8:18 PM Ibrar Ahmed <ibrar.ahmad@gmail.com> wrote:\n>\n> The patch does not apply, and rebase is required.\n>\n\nAttached a rebased patch (minor updates to the test code).\n\nRegards,\nGreg Nancarrow\nFujitsu Australia", "msg_date": "Mon, 19 Jul 2021 23:25:06 +1000", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Re[3]: On login trigger: take three" }, { "msg_contents": "Hi Greg,\n  \n>Среда, 7 июля 2021, 3:55 +03:00 от Greg Nancarrow <gregn4422@gmail.com>:\n> \n>On Sun, Jul 4, 2021 at 1:21 PM vignesh C < vignesh21@gmail.com > wrote:\n>>\n>> CFBot shows the following failure:\n>> # poll_query_until timed out executing this query:\n>> # SELECT '0/3046250' <= replay_lsn AND state = 'streaming' FROM\n>> pg_catalog.pg_stat_replication WHERE application_name = 'standby_1';\n>> # expecting this output:\n>> # t\n>> # last actual query output:\n>> # t\n>> # with stderr:\n>> # NOTICE: You are welcome!\n>> # Looks like your test exited with 29 before it could output anything.\n>> t/001_stream_rep.pl ..................\n>> Dubious, test returned 29 (wstat 7424, 0x1d00)\n>>\n>Thanks.\n>I found that the patch was broken by commit f452aaf7d (the part\n>\"adjust poll_query_until to insist on empty stderr as well as a stdout\n>match\").\n>So I had to remove a \"RAISE NOTICE\" (which was just an informational\n>message) from the login trigger function, to satisfy the new\n>poll_query_until expectations.\n\nDoes it mean that \"RAISE NOTICE\" should’t be used, or behaves unexpectedly in logon triggers? Should we mention this in the docs?\n \nRegards,\nIvan Panchenko\n>Also, I updated a PG14 version check (now must check PG15 version).\n>\n>Regards,\n>Greg Nancarrow\n>Fujitsu Australia\n \n Hi Greg, Среда, 7 июля 2021, 3:55 +03:00 от Greg Nancarrow <gregn4422@gmail.com>: On Sun, Jul 4, 2021 at 1:21 PM vignesh C <vignesh21@gmail.com> wrote:>> CFBot shows the following failure:> # poll_query_until timed out executing this query:> # SELECT '0/3046250' <= replay_lsn AND state = 'streaming' FROM> pg_catalog.pg_stat_replication WHERE application_name = 'standby_1';> # expecting this output:> # t> # last actual query output:> # t> # with stderr:> # NOTICE: You are welcome!> # Looks like your test exited with 29 before it could output anything.> t/001_stream_rep.pl ..................> Dubious, test returned 29 (wstat 7424, 0x1d00)>Thanks.I found that the patch was broken by commit f452aaf7d (the part\"adjust poll_query_until to insist on empty stderr as well as a stdoutmatch\").So I had to remove a \"RAISE NOTICE\" (which was just an informationalmessage) from the login trigger function, to satisfy the newpoll_query_until expectations.Does it mean that \"RAISE NOTICE\" should’t be used, or behaves unexpectedly in logon triggers? Should we mention this in the docs? Regards,Ivan PanchenkoAlso, I updated a PG14 version check (now must check PG15 version).Regards,Greg NancarrowFujitsu Australia", "msg_date": "Mon, 16 Aug 2021 18:11:42 +0300", "msg_from": "=?UTF-8?B?SXZhbiBQYW5jaGVua28=?= <wao@mail.ru>", "msg_from_op": false, "msg_subject": "=?UTF-8?B?UmVbNV06IE9uIGxvZ2luIHRyaWdnZXI6IHRha2UgdGhyZWU=?=" }, { "msg_contents": "On Tue, Aug 17, 2021 at 1:11 AM Ivan Panchenko <wao@mail.ru> wrote:\n>\n> Does it mean that \"RAISE NOTICE\" should’t be used, or behaves unexpectedly in logon triggers? Should we mention this in the docs?\n>\n\nNo I don't believe so, it was just that that part of the test\nframework (sub poll_query_until) had been changed to regard anything\noutput to stderr as an error (so now for the test to succeed, whatever\nis printed to stdout must match the expected test output, and stderr\nmust be empty).\n\nRegards,\nGreg Nancarrow\nFujitsu Australia\n\n\n", "msg_date": "Tue, 17 Aug 2021 10:07:03 +1000", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Re[5]: On login trigger: take three" }, { "msg_contents": "> On 19 Jul 2021, at 15:25, Greg Nancarrow <gregn4422@gmail.com> wrote:\n\n> Attached a rebased patch (minor updates to the test code).\n\nI took a look at this, and while I like the proposed feature I think the patch\nhas a bit more work required.\n\n\n+ END IF;\n+\n+-- 2) Initialize some user session data\n+ CREATE TEMP TABLE session_storage (x float, y integer);\nThe example in the documentation use a mix of indentations, neither of which is\nthe 2-space indentation used elsewhere in the docs.\n\n\n+\t/* Get the command tag. */\n+\ttag = parsetree ? CreateCommandTag(parsetree) : CMDTAG_CONNECT;\nThis is hardcoding knowledge that currently only this trigger wont have a\nparsetree, and setting the tag accordingly. This should instead check the\nevent and set CMDTAG_UNKNOWN if it isn't the expected one.\n\n\n+\t/* database has on-login triggers */\n+\tbool\t\tdathaslogontriggers;\nThis patch uses three different names for the same thing: client connection,\nlogontrigger and login trigger. Since this trigger only fires after successful\nauthentication it’s not accurate to name it client connection, as that implies\nit running on connections rather than logins. The nomenclature used in the\ntree is \"login\" so the patch should be adjusted everywhere to use that.\n\n\n+/* Hook for plugins to get control at start of session */\n+client_connection_hook_type client_connection_hook = EventTriggerOnConnect;\nI don't see the reason for adding core functionality by hooks. Having a hook\nmight be a useful thing on its own (to be discussed in a new thread, not hidden\nhere), but core functionality should not depend on it IMO.\n\n\n+\t{\"enable_client_connection_trigger\", PGC_SU_BACKEND, DEVELOPER_OPTIONS,\n+\t\tgettext_noop(\"Enables the client_connection event trigger.\"),\n+\t\tgettext_noop(\"In case of errors in the ON client_connection EVENT TRIGGER procedure, \"\n ..and..\n+\t/*\n+\t * Try to ignore error for superuser to make it possible to login even in case of errors\n+\t * during trigger execution\n+\t */\n+\tif (!is_superuser)\n+\t\tPG_RE_THROW();\nThis patch adds two ways for superusers to bypass this event trigger in case of\nit being faulty, but for every other event trigger we've documented to restart\nin single-user mode and fixing it there. Why does this need to be different?\nThis clearly has a bigger chance of being a footgun but I don't see that as a\nreason to add a GUC and a bypass that other footguns lack.\n\n\n+\telog(NOTICE, \"client_connection trigger failed with message: %s\", error->message);\nCalling elog() in a PG_CATCH() block isn't allowed is it?\n\n\n+\t/* Runtlist is empty: clear dathaslogontriggers flag\n+\t */\ns/Runtlist/Runlist/ and also commenting style.\n\n\nThe logic for resetting the pg_database flag when firing event trigger in case\nthe trigger has gone away is messy and a problem waiting to happen IMO. For\nnormal triggers we don't bother with that on the grounds of it being racy, and\ninstead perform relhastrigger removal during VACUUM. Another approach is using\na counter as propose upthread, since updating that can be made safer. The\ncurrent coding also isn't instructing concurrent backends to perform relcache\nrebuild.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Wed, 8 Sep 2021 14:56:42 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi\n\n\n> + {\"enable_client_connection_trigger\", PGC_SU_BACKEND,\n> DEVELOPER_OPTIONS,\n> + gettext_noop(\"Enables the client_connection event\n> trigger.\"),\n> + gettext_noop(\"In case of errors in the ON\n> client_connection EVENT TRIGGER procedure, \"\n> ..and..\n> + /*\n> + * Try to ignore error for superuser to make it possible to login\n> even in case of errors\n> + * during trigger execution\n> + */\n> + if (!is_superuser)\n> + PG_RE_THROW();\n> This patch adds two ways for superusers to bypass this event trigger in\n> case of\n> it being faulty, but for every other event trigger we've documented to\n> restart\n> in single-user mode and fixing it there. Why does this need to be\n> different?\n> This clearly has a bigger chance of being a footgun but I don't see that\n> as a\n> reason to add a GUC and a bypass that other footguns lack.\n>\n>\n>\nIn the time when event triggers were introduced, managed services were not\ntoo widely used like now. When we discussed this feature we thought about\nenvironments when users have no superuser rights and have no possibility to\ngo to single mode.\n\nPersonally, I prefer to introduce some bypassing for event triggers instead\nof removing bypass from login triggers.\n\nRegards\n\nPavel\n\nHi\n\n+       {\"enable_client_connection_trigger\", PGC_SU_BACKEND, DEVELOPER_OPTIONS,\n+               gettext_noop(\"Enables the client_connection event trigger.\"),\n+               gettext_noop(\"In case of errors in the ON client_connection EVENT TRIGGER procedure, \"\n ..and..\n+       /*\n+        * Try to ignore error for superuser to make it possible to login even in case of errors\n+        * during trigger execution\n+        */\n+       if (!is_superuser)\n+               PG_RE_THROW();\nThis patch adds two ways for superusers to bypass this event trigger in case of\nit being faulty, but for every other event trigger we've documented to restart\nin single-user mode and fixing it there.  Why does this need to be different?\nThis clearly has a bigger chance of being a footgun but I don't see that as a\nreason to add a GUC and a bypass that other footguns lack.\n\nIn the time when event triggers were introduced, managed services were not too widely used like now. When we discussed this feature we thought about environments when users have no superuser rights and have no possibility to go to single mode.Personally, I prefer to introduce some bypassing for event triggers instead of removing bypass from login triggers.RegardsPavel", "msg_date": "Wed, 8 Sep 2021 16:02:36 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 8 Sep 2021, at 16:02, Pavel Stehule <pavel.stehule@gmail.com> wrote:\n\n> In the time when event triggers were introduced, managed services were not too widely used like now. When we discussed this feature we thought about environments when users have no superuser rights and have no possibility to go to single mode.\n\nIn situations where you don't have superuser access and cannot restart in\nsingle user mode, none of the bypasses in this patch would help anyways.\n\nI understand the motivation, but continuing on even in the face of an\nereport(ERROR.. ) in the hopes of being able to turn off buggy code seems\npretty unsafe at best.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Wed, 8 Sep 2021 20:23:42 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "st 8. 9. 2021 v 20:23 odesílatel Daniel Gustafsson <daniel@yesql.se> napsal:\n\n> > On 8 Sep 2021, at 16:02, Pavel Stehule <pavel.stehule@gmail.com> wrote:\n>\n> > In the time when event triggers were introduced, managed services were\n> not too widely used like now. When we discussed this feature we thought\n> about environments when users have no superuser rights and have no\n> possibility to go to single mode.\n>\n> In situations where you don't have superuser access and cannot restart in\n> single user mode, none of the bypasses in this patch would help anyways.\n>\n\nIf I remember well, it should be possible - you can set GUC in connection\nstring, and this GUC is limited to the database owner.\n\n\n> I understand the motivation, but continuing on even in the face of an\n> ereport(ERROR.. ) in the hopes of being able to turn off buggy code seems\n> pretty unsafe at best.\n>\n\nI don't understand what you mean. I can disable the logon trigger by GUC. I\ncannot to enable an continue after an exception.\n\nRegards\n\nPavel\n\n\n>\n> --\n> Daniel Gustafsson https://vmware.com/\n>\n>\n\nst 8. 9. 2021 v 20:23 odesílatel Daniel Gustafsson <daniel@yesql.se> napsal:> On 8 Sep 2021, at 16:02, Pavel Stehule <pavel.stehule@gmail.com> wrote:\n\n> In the time when event triggers were introduced, managed services were not too widely used like now. When we discussed this feature we thought about environments when users have no superuser rights and have no possibility to go to single mode.\n\nIn situations where you don't have superuser access and cannot restart in\nsingle user mode, none of the bypasses in this patch would help anyways.If I remember well, it should be possible - you can set GUC in connection string, and this GUC is limited to the database owner.\n\nI understand the motivation, but continuing on even in the face of an\nereport(ERROR..  ) in the hopes of being able to turn off buggy code seems\npretty unsafe at best.I don't understand what you mean. I can disable the logon trigger by GUC. I cannot to enable an continue after an exception.RegardsPavel \n\n--\nDaniel Gustafsson               https://vmware.com/", "msg_date": "Wed, 8 Sep 2021 20:44:40 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Wed, Sep 8, 2021 at 10:56 PM Daniel Gustafsson <daniel@yesql.se> wrote:\n>\n> I took a look at this, and while I like the proposed feature I think the patch\n> has a bit more work required.\n>\n\nThanks for reviewing the patch.\nI am not the original patch author (who no longer seems active) but\nI've been contributing a bit and keeping the patch alive because I\nthink it's a worthwhile feature.\n\n>\n> +\n> +-- 2) Initialize some user session data\n> + CREATE TEMP TABLE session_storage (x float, y integer);\n> The example in the documentation use a mix of indentations, neither of which is\n> the 2-space indentation used elsewhere in the docs.\n>\n\nFixed, using 2-space indentation.\n(to be honest, the indentation seems inconsistent elsewhere in the\ndocs e.g. I'm seeing a nearby case of 2-space on 1st indent, 6-space\non 2nd indent)\n\n>\n> + /* Get the command tag. */\n> + tag = parsetree ? CreateCommandTag(parsetree) : CMDTAG_CONNECT;\n> This is hardcoding knowledge that currently only this trigger wont have a\n> parsetree, and setting the tag accordingly. This should instead check the\n> event and set CMDTAG_UNKNOWN if it isn't the expected one.\n>\n\nI updated that, but maybe not exactly how you expected?\n\n>\n> + /* database has on-login triggers */\n> + bool dathaslogontriggers;\n> This patch uses three different names for the same thing: client connection,\n> logontrigger and login trigger. Since this trigger only fires after successful\n> authentication it’s not accurate to name it client connection, as that implies\n> it running on connections rather than logins. The nomenclature used in the\n> tree is \"login\" so the patch should be adjusted everywhere to use that.\n>\n\nFixed.\n\n>\n> +/* Hook for plugins to get control at start of session */\n> +client_connection_hook_type client_connection_hook = EventTriggerOnConnect;\n> I don't see the reason for adding core functionality by hooks. Having a hook\n> might be a useful thing on its own (to be discussed in a new thread, not hidden\n> here), but core functionality should not depend on it IMO.\n>\n\nFair enough, I removed the hook.\n\n>\n> + {\"enable_client_connection_trigger\", PGC_SU_BACKEND, DEVELOPER_OPTIONS,\n> + gettext_noop(\"Enables the client_connection event trigger.\"),\n> + gettext_noop(\"In case of errors in the ON client_connection EVENT TRIGGER procedure, \"\n> ..and..\n> + /*\n> + * Try to ignore error for superuser to make it possible to login even in case of errors\n> + * during trigger execution\n> + */\n> + if (!is_superuser)\n> + PG_RE_THROW();\n> This patch adds two ways for superusers to bypass this event trigger in case of\n> it being faulty, but for every other event trigger we've documented to restart\n> in single-user mode and fixing it there. Why does this need to be different?\n> This clearly has a bigger chance of being a footgun but I don't see that as a\n> reason to add a GUC and a bypass that other footguns lack.\n>\n\nOK, I removed those bypasses. We'll see what others think.\n\n>\n> + elog(NOTICE, \"client_connection trigger failed with message: %s\", error->message);\n> Calling elog() in a PG_CATCH() block isn't allowed is it?\n>\n\nI believe it is allowed (e.g. there's a case in libpq), but I removed\nthis anyway as part of the superuser bypass.\n\n>\n> + /* Runtlist is empty: clear dathaslogontriggers flag\n> + */\n> s/Runtlist/Runlist/ and also commenting style.\n>\n\nFixed.\n\n>\n> The logic for resetting the pg_database flag when firing event trigger in case\n> the trigger has gone away is messy and a problem waiting to happen IMO. For\n> normal triggers we don't bother with that on the grounds of it being racy, and\n> instead perform relhastrigger removal during VACUUM. Another approach is using\n> a counter as propose upthread, since updating that can be made safer. The\n> current coding also isn't instructing concurrent backends to perform relcache\n> rebuild.\n>\n\nI think there are pros and cons of each possible approach, but I think\nI prefer the current way (which I have tweaked a bit) for similar\nreasons to those explained by the original patch author when debating\nwhether to use reference-counting instead, in the discussion upthread\n(e.g. it keeps it all in one place). Also, it seems to be more inline\nwith the documented reason why that pg_database flag was added in the\nfirst place. I have debugged a few concurrent scenarios with the\ncurrent mechanism in place. If you still dislike the logic for\nresetting the flag, please elaborate on the issues you foresee and one\nof the alternative approaches can be tried.\n\nI've attached the updated patch.\n\nRegards,\nGreg Nancarrow\nFujitsu Australia", "msg_date": "Wed, 15 Sep 2021 23:32:47 +1000", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi!\n\nNice feature, but, sorry, I see some design problem in suggested feature. AFAIK, \nthere is two use cases for this feature:\n1 A permission / prohibition to login some users\n2 Just a logging of facts of user's login\n\nSuggested patch proposes prohibition of login only by failing of login trigger \nand it has at least two issues:\n1 In case of prohibition to login, there is no clean way to store information \nabout unsuccessful login. Ok, it could be solved by dblink module but it seems \nto scary.\n2 For logging purpose failing of trigger will cause impossibility to login, it \ncould be workarounded by catching error in trigger function, but it's not so \nobvious for DBA.\n\nsome other issues:\n3 It's easy to create security hole, see attachment where non-privileged user \ncan close access to database even for superuser.\n4 Feature is not applicable for logging unsuccessful login with wrong \nusername/password or not matched by pg_hba.conf. Oracle could operate with such \ncases. But I don't think that this issue is a stopper for the patch.\n\nMay be, to solve that issues we could introduce return value of trigger and/or \nadd something like IGNORE ERROR to CREATE EVENT TRIGGER command.\n\nOn 15.09.2021 16:32, Greg Nancarrow wrote:\n> On Wed, Sep 8, 2021 at 10:56 PM Daniel Gustafsson <daniel@yesql.se> wrote:\n>>\n>> I took a look at this, and while I like the proposed feature I think the patch\n>> has a bit more work required.\n>>\n> \n> Thanks for reviewing the patch.\n> I am not the original patch author (who no longer seems active) but\n> I've been contributing a bit and keeping the patch alive because I\n> think it's a worthwhile feature.\n> \n>>\n>> +\n>> +-- 2) Initialize some user session data\n>> + CREATE TEMP TABLE session_storage (x float, y integer);\n>> The example in the documentation use a mix of indentations, neither of which is\n>> the 2-space indentation used elsewhere in the docs.\n>>\n> \n> Fixed, using 2-space indentation.\n> (to be honest, the indentation seems inconsistent elsewhere in the\n> docs e.g. I'm seeing a nearby case of 2-space on 1st indent, 6-space\n> on 2nd indent)\n> \n>>\n>> + /* Get the command tag. */\n>> + tag = parsetree ? CreateCommandTag(parsetree) : CMDTAG_CONNECT;\n>> This is hardcoding knowledge that currently only this trigger wont have a\n>> parsetree, and setting the tag accordingly. This should instead check the\n>> event and set CMDTAG_UNKNOWN if it isn't the expected one.\n>>\n> \n> I updated that, but maybe not exactly how you expected?\n> \n>>\n>> + /* database has on-login triggers */\n>> + bool dathaslogontriggers;\n>> This patch uses three different names for the same thing: client connection,\n>> logontrigger and login trigger. Since this trigger only fires after successful\n>> authentication it’s not accurate to name it client connection, as that implies\n>> it running on connections rather than logins. The nomenclature used in the\n>> tree is \"login\" so the patch should be adjusted everywhere to use that.\n>>\n> \n> Fixed.\n> \n>>\n>> +/* Hook for plugins to get control at start of session */\n>> +client_connection_hook_type client_connection_hook = EventTriggerOnConnect;\n>> I don't see the reason for adding core functionality by hooks. Having a hook\n>> might be a useful thing on its own (to be discussed in a new thread, not hidden\n>> here), but core functionality should not depend on it IMO.\n>>\n> \n> Fair enough, I removed the hook.\n> \n>>\n>> + {\"enable_client_connection_trigger\", PGC_SU_BACKEND, DEVELOPER_OPTIONS,\n>> + gettext_noop(\"Enables the client_connection event trigger.\"),\n>> + gettext_noop(\"In case of errors in the ON client_connection EVENT TRIGGER procedure, \"\n>> ..and..\n>> + /*\n>> + * Try to ignore error for superuser to make it possible to login even in case of errors\n>> + * during trigger execution\n>> + */\n>> + if (!is_superuser)\n>> + PG_RE_THROW();\n>> This patch adds two ways for superusers to bypass this event trigger in case of\n>> it being faulty, but for every other event trigger we've documented to restart\n>> in single-user mode and fixing it there. Why does this need to be different?\n>> This clearly has a bigger chance of being a footgun but I don't see that as a\n>> reason to add a GUC and a bypass that other footguns lack.\n>>\n> \n> OK, I removed those bypasses. We'll see what others think.\n> \n>>\n>> + elog(NOTICE, \"client_connection trigger failed with message: %s\", error->message);\n>> Calling elog() in a PG_CATCH() block isn't allowed is it?\n>>\n> \n> I believe it is allowed (e.g. there's a case in libpq), but I removed\n> this anyway as part of the superuser bypass.\n> \n>>\n>> + /* Runtlist is empty: clear dathaslogontriggers flag\n>> + */\n>> s/Runtlist/Runlist/ and also commenting style.\n>>\n> \n> Fixed.\n> \n>>\n>> The logic for resetting the pg_database flag when firing event trigger in case\n>> the trigger has gone away is messy and a problem waiting to happen IMO. For\n>> normal triggers we don't bother with that on the grounds of it being racy, and\n>> instead perform relhastrigger removal during VACUUM. Another approach is using\n>> a counter as propose upthread, since updating that can be made safer. The\n>> current coding also isn't instructing concurrent backends to perform relcache\n>> rebuild.\n>>\n> \n> I think there are pros and cons of each possible approach, but I think\n> I prefer the current way (which I have tweaked a bit) for similar\n> reasons to those explained by the original patch author when debating\n> whether to use reference-counting instead, in the discussion upthread\n> (e.g. it keeps it all in one place). Also, it seems to be more inline\n> with the documented reason why that pg_database flag was added in the\n> first place. I have debugged a few concurrent scenarios with the\n> current mechanism in place. If you still dislike the logic for\n> resetting the flag, please elaborate on the issues you foresee and one\n> of the alternative approaches can be tried.\n> \n> I've attached the updated patch.\n> \n> Regards,\n> Greg Nancarrow\n> Fujitsu Australia\n> \n\n-- \nTeodor Sigaev E-mail: teodor@sigaev.ru\n WWW: http://www.sigaev.ru/", "msg_date": "Wed, 29 Sep 2021 15:14:42 +0300", "msg_from": "Teodor Sigaev <teodor@sigaev.ru>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Wed, Sep 29, 2021 at 10:14 PM Teodor Sigaev <teodor@sigaev.ru> wrote:\n>\n> Nice feature, but, sorry, I see some design problem in suggested feature. AFAIK,\n> there is two use cases for this feature:\n> 1 A permission / prohibition to login some users\n> 2 Just a logging of facts of user's login\n>\n> Suggested patch proposes prohibition of login only by failing of login trigger\n> and it has at least two issues:\n> 1 In case of prohibition to login, there is no clean way to store information\n> about unsuccessful login. Ok, it could be solved by dblink module but it seems\n> to scary.\n\nIt's an area that could be improved, but the patch is more intended to\nallow additional actions on successful login, as described by the\nfollowing (taken from the doc updates in the patch):\n\n+ <para>\n+ The event trigger on the <literal>login</literal> event can be\n+ useful for logging user logins, for verifying the connection and\n+ assigning roles according to current circumstances, or for some\nsession data\n+ initialization.\n+ </para>\n\n> 2 For logging purpose failing of trigger will cause impossibility to login, it\n> could be workarounded by catching error in trigger function, but it's not so\n> obvious for DBA.\n>\n\nIf you look back on the past discussions on this thread, you'll see\nthat originally the patch added a GUC for the purpose of allowing\nsuperusers to disable the event trigger, to allow login in this case.\nHowever it was argued that there was already a documented way of\nbypassing buggy event triggers (i.e. restart in single-user mode), so\nthat GUC was removed.\nAlso previously in the patch, login trigger errors for superusers were\nignored in order to allow them to login in this case, but it was\nargued that it could well be unsafe to continue on after an error, so\nthat too was removed.\nSee below:\n\n>\n> + {\"enable_client_connection_trigger\", PGC_SU_BACKEND, DEVELOPER_OPTIONS,\n> + gettext_noop(\"Enables the client_connection event trigger.\"),\n> + gettext_noop(\"In case of errors in the ON client_connection EVENT TRIGGER procedure, \"\n> ..and..\n> + /*\n> + * Try to ignore error for superuser to make it possible to login even in case of errors\n> + * during trigger execution\n> + */\n> + if (!is_superuser)\n> + PG_RE_THROW();\n> This patch adds two ways for superusers to bypass this event trigger in case of\n> it being faulty, but for every other event trigger we've documented to restart\n> in single-user mode and fixing it there. Why does this need to be different?\n> This clearly has a bigger chance of being a footgun but I don't see that as a\n> reason to add a GUC and a bypass that other footguns lack.\n>\n\nSo I really don't think that a failing event trigger will cause an\n\"impossibility to login\".\nThe patch updates the documentation to explain the use of single-user\nmode to fix buggy login event triggers. See below:\n\n+ <para>\n+ The <literal>login</literal> event occurs when a user logs in to the\n+ system.\n+ Any bugs in a trigger procedure for this event may prevent successful\n+ login to the system. Such bugs may be fixed after first restarting the\n+ system in single-user mode (as event triggers are disabled in this mode).\n+ See the <xref linkend=\"app-postgres\"/> reference page for details about\n+ using single-user mode.\n+ </para>\n+\n\nRegards,\nGreg Nancarrow\nFujitsu Australia\n\n\n", "msg_date": "Thu, 30 Sep 2021 12:15:15 +1000", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 30 Sep 2021, at 04:15, Greg Nancarrow <gregn4422@gmail.com> wrote:\n> \n> On Wed, Sep 29, 2021 at 10:14 PM Teodor Sigaev <teodor@sigaev.ru> wrote:\n>> \n>> Nice feature, but, sorry, I see some design problem in suggested feature. AFAIK,\n>> there is two use cases for this feature:\n>> 1 A permission / prohibition to login some users\n>> 2 Just a logging of facts of user's login\n>> \n>> Suggested patch proposes prohibition of login only by failing of login trigger\n>> and it has at least two issues:\n>> 1 In case of prohibition to login, there is no clean way to store information\n>> about unsuccessful login. Ok, it could be solved by dblink module but it seems\n>> to scary.\n> \n> It's an area that could be improved, but the patch is more intended to\n> allow additional actions on successful login, as described by the\n> following (taken from the doc updates in the patch):\n> \n> + <para>\n> + The event trigger on the <literal>login</literal> event can be\n> + useful for logging user logins, for verifying the connection and\n> + assigning roles according to current circumstances, or for some\n> session data\n> + initialization.\n> + </para>\n\nRunning user code with potential side effects on unsuccessful logins also open\nup the risk for (D)DoS attacks.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Thu, 30 Sep 2021 11:06:51 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Wed, Sep 15, 2021 at 11:32 PM Greg Nancarrow <gregn4422@gmail.com> wrote:\n>\n> I've attached the updated patch.\n>\n\nAttached a rebased version of the patch, as it was broken by fairly\nrecent changes (only very minor change to the previous version).\n\nRegards,\nGreg Nancarrow\nFujitsu Australia", "msg_date": "Tue, 5 Oct 2021 15:25:26 +1100", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Dear colleagues, \nPlease see my suggestions below and the updated patch attached.\n \n \n \n \n  \n>Среда, 29 сентября 2021, 15:14 +03:00 от Teodor Sigaev < teodor@sigaev.ru >:\n> \n>Hi!\n>\n>Nice feature, but, sorry, I see some design problem in suggested feature. AFAIK,\n>there is two use cases for this feature:\n>1 A permission / prohibition to login some users\n>2 Just a logging of facts of user's login\n>\n>Suggested patch proposes prohibition of login only by failing of login trigger\n>and it has at least two issues:\n>1 In case of prohibition to login, there is no clean way to store information\n>about unsuccessful login. Ok, it could be solved by dblink module but it seems\n>to scary.\nThis is a common problem of logging errors and unsuccessful transactions of any kind. It can be solved by:\n- logging to external log storage (stupid logging to files or syslog or whatever you can imagine with PL/Perl (sorry))\n- logging inside the database by db_link or through background worker (like described in https://dpavlin.wordpress.com/2017/05/09/david-rader-autonomous-transactions-using-pg_background/ )\n- or by implementing autonomous transactions in PostgreSQL, which is already under development by some of my and Teodor’s colleagues.\n \nSo I propose not to invent another solution to this common problem here.\n>2 For logging purpose failing of trigger will cause impossibility to login, it\n>could be workarounded by catching error in trigger function, but it's not so\n>obvious for DBA.\nIf the trigger contains an error, nobody can login. The database is bricked.\nPrevious variant of the patch proposed to fix this with going to single-user mode.\nFor faster recovery I propose to have also a GUC variable to turn on/off the login triggers. It should be 'on' by default.\n>\n>some other issues:\n>3 It's easy to create security hole, see attachment where non-privileged user\n>can close access to database even for superuser.\nSuch cases can be avoided by careful design of the login triggers and related permissions. Added such note to the documentation.\n>4 Feature is not applicable for logging unsuccessful login with wrong\n>username/password or not matched by pg_hba.conf. Oracle could operate with such\n>cases. But I don't think that this issue is a stopper for the patch.\nYes. Btw, note that pg_hba functionality can be implemented completely inside the login trigger :) !\n>\n>May be, to solve that issues we could introduce return value of trigger and/or\n>add something like IGNORE ERROR to CREATE EVENT TRIGGER command.\nAny solutions which make syntax more complicated can lead Postgres to become Oracle (in the worst sense). I do not like this.\n\nA new version of the patch is attached. It applies to the current master and contains the above mentioned GUC code, relevant tests and docs.\nRegards,\nIvan Panchenko\n>\n>On 15.09.2021 16:32, Greg Nancarrow wrote:\n>> On Wed, Sep 8, 2021 at 10:56 PM Daniel Gustafsson < daniel@yesql.se > wrote:\n>>>\n>>> I took a look at this, and while I like the proposed feature I think the patch\n>>> has a bit more work required.\n>>>\n>>\n>> Thanks for reviewing the patch.\n>> I am not the original patch author (who no longer seems active) but\n>> I've been contributing a bit and keeping the patch alive because I\n>> think it's a worthwhile feature.\n>>\n>>>\n>>> +\n>>> +-- 2) Initialize some user session data\n>>> + CREATE TEMP TABLE session_storage (x float, y integer);\n>>> The example in the documentation use a mix of indentations, neither of which is\n>>> the 2-space indentation used elsewhere in the docs.\n>>>\n>>\n>> Fixed, using 2-space indentation.\n>> (to be honest, the indentation seems inconsistent elsewhere in the\n>> docs e.g. I'm seeing a nearby case of 2-space on 1st indent, 6-space\n>> on 2nd indent)\n>>\n>>>\n>>> + /* Get the command tag. */\n>>> + tag = parsetree ? CreateCommandTag(parsetree) : CMDTAG_CONNECT;\n>>> This is hardcoding knowledge that currently only this trigger wont have a\n>>> parsetree, and setting the tag accordingly. This should instead check the\n>>> event and set CMDTAG_UNKNOWN if it isn't the expected one.\n>>>\n>>\n>> I updated that, but maybe not exactly how you expected?\n>>\n>>>\n>>> + /* database has on-login triggers */\n>>> + bool dathaslogontriggers;\n>>> This patch uses three different names for the same thing: client connection,\n>>> logontrigger and login trigger. Since this trigger only fires after successful\n>>> authentication it’s not accurate to name it client connection, as that implies\n>>> it running on connections rather than logins. The nomenclature used in the\n>>> tree is \"login\" so the patch should be adjusted everywhere to use that.\n>>>\n>>\n>> Fixed.\n>>\n>>>\n>>> +/* Hook for plugins to get control at start of session */\n>>> +client_connection_hook_type client_connection_hook = EventTriggerOnConnect;\n>>> I don't see the reason for adding core functionality by hooks. Having a hook\n>>> might be a useful thing on its own (to be discussed in a new thread, not hidden\n>>> here), but core functionality should not depend on it IMO.\n>>>\n>>\n>> Fair enough, I removed the hook.\n>>\n>>>\n>>> + {\"enable_client_connection_trigger\", PGC_SU_BACKEND, DEVELOPER_OPTIONS,\n>>> + gettext_noop(\"Enables the client_connection event trigger.\"),\n>>> + gettext_noop(\"In case of errors in the ON client_connection EVENT TRIGGER procedure, \"\n>>> ..and..\n>>> + /*\n>>> + * Try to ignore error for superuser to make it possible to login even in case of errors\n>>> + * during trigger execution\n>>> + */\n>>> + if (!is_superuser)\n>>> + PG_RE_THROW();\n>>> This patch adds two ways for superusers to bypass this event trigger in case of\n>>> it being faulty, but for every other event trigger we've documented to restart\n>>> in single-user mode and fixing it there. Why does this need to be different?\n>>> This clearly has a bigger chance of being a footgun but I don't see that as a\n>>> reason to add a GUC and a bypass that other footguns lack.\n>>>\n>>\n>> OK, I removed those bypasses. We'll see what others think.\n>>\n>>>\n>>> + elog(NOTICE, \"client_connection trigger failed with message: %s\", error->message);\n>>> Calling elog() in a PG_CATCH() block isn't allowed is it?\n>>>\n>>\n>> I believe it is allowed (e.g. there's a case in libpq), but I removed\n>> this anyway as part of the superuser bypass.\n>>\n>>>\n>>> + /* Runtlist is empty: clear dathaslogontriggers flag\n>>> + */\n>>> s/Runtlist/Runlist/ and also commenting style.\n>>>\n>>\n>> Fixed.\n>>\n>>>\n>>> The logic for resetting the pg_database flag when firing event trigger in case\n>>> the trigger has gone away is messy and a problem waiting to happen IMO. For\n>>> normal triggers we don't bother with that on the grounds of it being racy, and\n>>> instead perform relhastrigger removal during VACUUM. Another approach is using\n>>> a counter as propose upthread, since updating that can be made safer. The\n>>> current coding also isn't instructing concurrent backends to perform relcache\n>>> rebuild.\n>>>\n>>\n>> I think there are pros and cons of each possible approach, but I think\n>> I prefer the current way (which I have tweaked a bit) for similar\n>> reasons to those explained by the original patch author when debating\n>> whether to use reference-counting instead, in the discussion upthread\n>> (e.g. it keeps it all in one place). Also, it seems to be more inline\n>> with the documented reason why that pg_database flag was added in the\n>> first place. I have debugged a few concurrent scenarios with the\n>> current mechanism in place. If you still dislike the logic for\n>> resetting the flag, please elaborate on the issues you foresee and one\n>> of the alternative approaches can be tried.\n>>\n>> I've attached the updated patch.\n>>\n>> Regards,\n>> Greg Nancarrow\n>> Fujitsu Australia\n>>\n>--\n>Teodor Sigaev E-mail: teodor@sigaev.ru\n>                                                    WWW: http://www.sigaev.ru/", "msg_date": "Wed, 03 Nov 2021 19:15:18 +0300", "msg_from": "=?UTF-8?B?SXZhbiBQYW5jaGVua28=?= <wao@mail.ru>", "msg_from_op": false, "msg_subject": "=?UTF-8?B?UmVbMl06IE9uIGxvZ2luIHRyaWdnZXI6IHRha2UgdGhyZWU=?=" }, { "msg_contents": "> On 3 Nov 2021, at 17:15, Ivan Panchenko <wao@mail.ru> wrote:\n> Среда, 29 сентября 2021, 15:14 +03:00 от Teodor Sigaev <teodor@sigaev.ru <x-msg://33/compose?To=teodor@sigaev.ru>>:\n> 2 For logging purpose failing of trigger will cause impossibility to login, it\n> could be workarounded by catching error in trigger function, but it's not so\n> obvious for DBA.\n> If the trigger contains an error, nobody can login. The database is bricked.\n> Previous variant of the patch proposed to fix this with going to single-user mode.\n> For faster recovery I propose to have also a GUC variable to turn on/off the login triggers.\n> It should be 'on' by default.\n\nAs voiced earlier, I disagree with this and I dislike the idea of punching a\nhole for circumventing infrastructure intended for auditing.\n\nUse-cases for a login-trigger commonly involve audit trail logging, session\ninitialization etc. If the login trigger bricks the production database to the\nextent that it needs to be restarted with the magic GUC, then it's highly\nlikely that you *don't* want regular connections to the database for the\nduration of this. Any such connection won't be subject to what the trigger\ndoes which seem counter to having the trigger in the first place. This means\nthat it's likely that the superuser fixing it will have to disable logins for\neveryone else while fixing, and it quicly becomes messy.\n\nWith that in mind, I think single-user mode actually *helps* the users in this\ncase, and we avoid a hole punched which in worst case can be a vector for an\nattack.\n\nMaybe I'm overly paranoid, but adding a backdoor of sorts for a situation which\nreally shouldn't happen doesn't seem like a good idea.\n> some other issues:\n> 3 It's easy to create security hole, see attachment where non-privileged user\n> can close access to database even for superuser.\n> Such cases can be avoided by careful design of the login triggers and related permissions. Added such note to the documentation.\n\nIf all login triggers are written carefully like that, we don't need the GUC to\ndisable them?\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Wed, 3 Nov 2021 21:43:07 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Thu, Nov 4, 2021 at 7:43 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n\n> > On 3 Nov 2021, at 17:15, Ivan Panchenko <wao@mail.ru> wrote:\n> > Среда, 29 сентября 2021, 15:14 +03:00 от Teodor Sigaev <teodor@sigaev.ru\n> <x-msg://33/compose?To=teodor@sigaev.ru>>:\n> > 2 For logging purpose failing of trigger will cause impossibility to\n> login, it\n> > could be workarounded by catching error in trigger function, but it's\n> not so\n> > obvious for DBA.\n> > If the trigger contains an error, nobody can login. The database is\n> bricked.\n> > Previous variant of the patch proposed to fix this with going to\n> single-user mode.\n> > For faster recovery I propose to have also a GUC variable to turn on/off\n> the login triggers.\n> > It should be 'on' by default.\n>\n> As voiced earlier, I disagree with this and I dislike the idea of punching\n> a\n> hole for circumventing infrastructure intended for auditing.\n>\n> Use-cases for a login-trigger commonly involve audit trail logging, session\n> initialization etc. If the login trigger bricks the production database\n> to the\n> extent that it needs to be restarted with the magic GUC, then it's highly\n> likely that you *don't* want regular connections to the database for the\n> duration of this. Any such connection won't be subject to what the trigger\n> does which seem counter to having the trigger in the first place. This\n> means\n> that it's likely that the superuser fixing it will have to disable logins\n> for\n> everyone else while fixing, and it quicly becomes messy.\n>\n> With that in mind, I think single-user mode actually *helps* the users in\n> this\n> case, and we avoid a hole punched which in worst case can be a vector for\n> an\n> attack.\n>\n> Maybe I'm overly paranoid, but adding a backdoor of sorts for a situation\n> which\n> really shouldn't happen doesn't seem like a good idea.\n>\n>\n+1\nThe arguments given are pretty convincing IMHO, and I agree that the\nadditions made in the v20 patch are not a good idea, and are not needed.\n\n\nRegards,\nGreg Nancarrow\nFujitsu Australia\n\nOn Thu, Nov 4, 2021 at 7:43 AM Daniel Gustafsson <daniel@yesql.se> wrote:> On 3 Nov 2021, at 17:15, Ivan Panchenko <wao@mail.ru> wrote:\n> Среда, 29 сентября 2021, 15:14 +03:00 от Teodor Sigaev <teodor@sigaev.ru <x-msg://33/compose?To=teodor@sigaev.ru>>:\n> 2 For logging purpose failing of trigger will cause impossibility to login, it\n> could be workarounded by catching error in trigger function, but it's not so\n> obvious for DBA.\n> If the trigger contains an error, nobody can login. The database is bricked.\n> Previous variant of the patch proposed to fix this with going to single-user mode.\n> For faster recovery I propose to have also a GUC variable to turn on/off the login triggers.\n> It should be 'on' by default.\n\nAs voiced earlier, I disagree with this and I dislike the idea of punching a\nhole for circumventing infrastructure intended for auditing.\n\nUse-cases for a login-trigger commonly involve audit trail logging, session\ninitialization etc.  If the login trigger bricks the production database to the\nextent that it needs to be restarted with the magic GUC, then it's highly\nlikely that you *don't* want regular connections to the database for the\nduration of this.  Any such connection won't be subject to what the trigger\ndoes which seem counter to having the trigger in the first place.  This means\nthat it's likely that the superuser fixing it will have to disable logins for\neveryone else while fixing, and it quicly becomes messy.\n\nWith that in mind, I think single-user mode actually *helps* the users in this\ncase, and we avoid a hole punched which in worst case can be a vector for an\nattack.\n\nMaybe I'm overly paranoid, but adding a backdoor of sorts for a situation which\nreally shouldn't happen doesn't seem like a good idea.+1The arguments given are pretty convincing IMHO, and I agree that the additions made in the v20 patch are not a good idea, and are not needed.Regards,Greg NancarrowFujitsu Australia", "msg_date": "Fri, 5 Nov 2021 15:03:08 +1100", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Fri, Nov 5, 2021 at 3:03 PM Greg Nancarrow <gregn4422@gmail.com> wrote:\n>\n> +1\n> The arguments given are pretty convincing IMHO, and I agree that the additions made in the v20 patch are not a good idea, and are not needed.\n>\n\nIf there are no objections, I plan to reinstate the previous v19 patch\n(as v21), perhaps with a few minor improvements and cleanups (e.g. SQL\ncapitalization) in the tests, as hinted at in the v20 patch, but no\nnew functionality.\n\nRegards,\nGreg Nancarrow\nFujitsu Australia\n\n\n", "msg_date": "Wed, 10 Nov 2021 18:12:34 +1100", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 10 Nov 2021, at 08:12, Greg Nancarrow <gregn4422@gmail.com> wrote:\n> \n> On Fri, Nov 5, 2021 at 3:03 PM Greg Nancarrow <gregn4422@gmail.com> wrote:\n>> \n>> +1\n>> The arguments given are pretty convincing IMHO, and I agree that the additions made in the v20 patch are not a good idea, and are not needed.\n> \n> If there are no objections, I plan to reinstate the previous v19 patch\n> (as v21), perhaps with a few minor improvements and cleanups (e.g. SQL\n> capitalization) in the tests, as hinted at in the v20 patch, but no\n> new functionality.\n\nNo objections from me. Small nitpicks from the v19 patch:\n\n+ This flag is used internally by Postgres and should not be manually changed by DBA or application.\nThis should be <productname>PostgreSQL</productname>.\n\n+\t * There can be a race condition: a login event trigger may have\n..\n+\t/* Fire any defined login triggers, if appropriate */\nThe patch say \"login trigger\" in most places, and \"login event trigger\" in a\nfew places. We should settle for a single nomenclature, and I think \"login\nevent trigger\" is the best option.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Wed, 10 Nov 2021 10:11:56 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "st 10. 11. 2021 v 10:11 odesílatel Daniel Gustafsson <daniel@yesql.se>\nnapsal:\n\n> > On 10 Nov 2021, at 08:12, Greg Nancarrow <gregn4422@gmail.com> wrote:\n> >\n> > On Fri, Nov 5, 2021 at 3:03 PM Greg Nancarrow <gregn4422@gmail.com>\n> wrote:\n> >>\n> >> +1\n> >> The arguments given are pretty convincing IMHO, and I agree that the\n> additions made in the v20 patch are not a good idea, and are not needed.\n> >\n> > If there are no objections, I plan to reinstate the previous v19 patch\n> > (as v21), perhaps with a few minor improvements and cleanups (e.g. SQL\n> > capitalization) in the tests, as hinted at in the v20 patch, but no\n> > new functionality.\n>\n> No objections from me. Small nitpicks from the v19 patch:\n>\n\nok,\n\nRegards\n\nPavel\n\n\n> + This flag is used internally by Postgres and should not be\n> manually changed by DBA or application.\n> This should be <productname>PostgreSQL</productname>.\n>\n> + * There can be a race condition: a login event trigger may have\n> ..\n> + /* Fire any defined login triggers, if appropriate */\n> The patch say \"login trigger\" in most places, and \"login event trigger\" in\n> a\n> few places. We should settle for a single nomenclature, and I think \"login\n> event trigger\" is the best option.\n>\n> --\n> Daniel Gustafsson https://vmware.com/\n>\n>\n\nst 10. 11. 2021 v 10:11 odesílatel Daniel Gustafsson <daniel@yesql.se> napsal:> On 10 Nov 2021, at 08:12, Greg Nancarrow <gregn4422@gmail.com> wrote:\n> \n> On Fri, Nov 5, 2021 at 3:03 PM Greg Nancarrow <gregn4422@gmail.com> wrote:\n>> \n>> +1\n>> The arguments given are pretty convincing IMHO, and I agree that the additions made in the v20 patch are not a good idea, and are not needed.\n> \n> If there are no objections, I plan to reinstate the previous v19 patch\n> (as v21), perhaps with a few minor improvements and cleanups (e.g. SQL\n> capitalization) in the tests, as hinted at in the v20 patch, but no\n> new functionality.\n\nNo objections from me. Small nitpicks from the v19 patch:ok,RegardsPavel\n\n+        This flag is used internally by Postgres and should not be manually changed by DBA or application.\nThis should be <productname>PostgreSQL</productname>.\n\n+        * There can be a race condition: a login event trigger may have\n..\n+       /* Fire any defined login triggers, if appropriate */\nThe patch say \"login trigger\" in most places, and \"login event trigger\" in a\nfew places.  We should settle for a single nomenclature, and I think \"login\nevent trigger\" is the best option.\n\n--\nDaniel Gustafsson               https://vmware.com/", "msg_date": "Wed, 10 Nov 2021 18:05:54 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Wed, Nov 10, 2021 at 8:11 PM Daniel Gustafsson <daniel@yesql.se> wrote:\n>\n> > If there are no objections, I plan to reinstate the previous v19 patch\n> > (as v21), perhaps with a few minor improvements and cleanups (e.g. SQL\n> > capitalization) in the tests, as hinted at in the v20 patch, but no\n> > new functionality.\n>\n> No objections from me. Small nitpicks from the v19 patch:\n>\n> + This flag is used internally by Postgres and should not be manually changed by DBA or application.\n> This should be <productname>PostgreSQL</productname>.\n>\n> + * There can be a race condition: a login event trigger may have\n> ..\n> + /* Fire any defined login triggers, if appropriate */\n> The patch say \"login trigger\" in most places, and \"login event trigger\" in a\n> few places. We should settle for a single nomenclature, and I think \"login\n> event trigger\" is the best option.\n>\n\nI've attached an updated patch, that essentially reinstates the v19\npatch, but with a few improvements such as:\n- Updates to address nitpicks (Daniel Gustafsson)\n- dathaslogintriggers -> dathasloginevttriggers flag rename (too\nlong?) and remove its restoration in pg_dump output, since it's not\nneeded (as in v20 patch)\n- Some tidying of the updates to the event_trigger tests and\ncapitalization of the test SQL\n\nRegards,\nGreg Nancarrow\nFujitsu Australia", "msg_date": "Thu, 11 Nov 2021 17:37:46 +1100", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 11 Nov 2021, at 07:37, Greg Nancarrow <gregn4422@gmail.com> wrote:\n\n> I've attached an updated patch, that essentially reinstates the v19\n> patch\n\nThanks! I've only skimmed it so far but it looks good, will do a more thorough\nreview soon.\n\n+ This flag is used to avoid extra lookups on the pg_event_trigger table during each backend startup.\nThis should be <structname>pg_event_trigger</structname>. Sorry, missed that\none at that last read-through.\n\n> - dathaslogintriggers -> dathasloginevttriggers flag rename (too\n> long?)\n\nI'm not crazy about this name, \"evt\" is commonly the abbreviation of \"event\ntrigger\" (used in evtcache.c etc) so \"dathasloginevt\" would IMO be better.\nThat being said, that's still not a very readable name, maybe someone else has\nan even better suggestion?\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Thu, 11 Nov 2021 10:56:55 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Thu, Nov 11, 2021 at 8:56 PM Daniel Gustafsson <daniel@yesql.se> wrote:\n>\n> + This flag is used to avoid extra lookups on the pg_event_trigger table during each backend startup.\n> This should be <structname>pg_event_trigger</structname>. Sorry, missed that\n> one at that last read-through.\n>\nThanks, noted.\n\n> > - dathaslogintriggers -> dathasloginevttriggers flag rename (too\n> > long?)\n>\n> I'm not crazy about this name, \"evt\" is commonly the abbreviation of \"event\n> trigger\" (used in evtcache.c etc) so \"dathasloginevt\" would IMO be better.\n> That being said, that's still not a very readable name, maybe someone else has\n> an even better suggestion?\n>\nYes you're right, in this case I was wrongly treating \"evt\" as an\nabbreviation for \"event\".\nI agree \"dathasloginevt\" would be better.\n\n\nRegards,\nGreg Nancarrow\nFujitsu Australia\n\n\n", "msg_date": "Fri, 12 Nov 2021 09:44:06 +1100", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Thu, Nov 11, 2021 at 8:56 PM Daniel Gustafsson <daniel@yesql.se> wrote:\n>\n> + This flag is used to avoid extra lookups on the pg_event_trigger table during each backend startup.\n> This should be <structname>pg_event_trigger</structname>. Sorry, missed that\n> one at that last read-through.\n>\nFixed.\n\n> > - dathaslogintriggers -> dathasloginevttriggers flag rename (too\n> > long?)\n>\n> I'm not crazy about this name, \"evt\" is commonly the abbreviation of \"event\n> trigger\" (used in evtcache.c etc) so \"dathasloginevt\" would IMO be better.\n> That being said, that's still not a very readable name, maybe someone else has\n> an even better suggestion?\n>\nChanged to \"dathasloginevt\", as suggested.\n\nI've attached an updated patch with these changes.\nI also noticed one of the Windows-based cfbots was failing with an\n\"SSPI authentication failed for user\" error, so I updated the test\ncode for that.\n\nRegards,\nGreg Nancarrow\nFujitsu Australia", "msg_date": "Tue, 16 Nov 2021 16:38:33 +1100", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Tue, Nov 16, 2021 at 4:38 PM Greg Nancarrow <gregn4422@gmail.com> wrote:\n>\n> I've attached an updated patch with these changes.\n>\n\nI've attached a re-based version (no functional changes from the\nprevious) to fix cfbot failures.\n\nRegards,\nGreg Nancarrow\nFujitsu Australia", "msg_date": "Mon, 6 Dec 2021 12:10:29 +1100", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Mon, Dec 6, 2021 at 12:10 PM Greg Nancarrow <gregn4422@gmail.com> wrote:\n>\n> I've attached a re-based version (no functional changes from the\n> previous) to fix cfbot failures.\n>\n\nI've attached a re-based version (no functional changes from the\nprevious) to fix cfbot failures.\n\nRegards,\nGreg Nancarrow\nFujitsu Australia", "msg_date": "Mon, 24 Jan 2022 13:59:02 +1100", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Mon, Jan 24, 2022 at 1:59 PM Greg Nancarrow <gregn4422@gmail.com> wrote:\n>\n> I've attached a re-based version (no functional changes from the\n> previous) to fix cfbot failures.\n>\n\nI've attached a re-based version (no functional changes from the\nprevious) to fix cfbot failures.\n\nRegards,\nGreg Nancarrow\nFujitsu Australia", "msg_date": "Tue, 15 Feb 2022 21:07:15 +1100", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 15 Feb 2022, at 11:07, Greg Nancarrow <gregn4422@gmail.com> wrote:\n\n> I've attached a re-based version (no functional changes from the\n> previous) to fix cfbot failures.\n\nThanks for adopting this patch, I took another look at it today and have some\ncomments.\n\n+ This flag is used internally by <productname>PostgreSQL</productname> and should not be manually changed by DBA or application.\nI think we should reword this to something like \"This flag is used internally\nby <productname>PostgreSQL</productname> and should not be altered or relied\nupon for monitoring\". We really don't want anyone touching or interpreting\nthis value since there is no guarantee that it will be accurate.\n\n\n+\tnew_record[Anum_pg_database_dathasloginevt - 1] = BoolGetDatum(datform->dathasloginevt);\nSince the corresponding new_record_repl valus is false, this won't do anything\nand can be removed. We will use the old value anyways.\n\n\n+\tif (strcmp(eventname, \"login\") == 0)\nI think this block warrants a comment on why it only applies to login triggers.\n\n\n+\t\tdb = (Form_pg_database) GETSTRUCT(tuple);\n+\t\tif (!db->dathasloginevt)\n+\t\t{\n+\t\t\tdb->dathasloginevt = true;\n+\t\t\tCatalogTupleUpdate(pg_db, &tuple->t_self, tuple);\n+\t\t}\n+\t\telse\n+\t\t\tCacheInvalidateRelcacheByTuple(tuple);\nThis needs a CommandCounterIncrement inside the if () { .. } block right?\n\n\n+\t/* Get the command tag. */\n+\ttag = (event == EVT_Login) ? CMDTAG_LOGIN : CreateCommandTag(parsetree);\nTo match project style I think this should be an if-then-else block. Also,\nwhile it's tempting to move this before the assertion block in order to reuse\nit there, it does mean that we are calling this in a hot codepath before we\nknow if it's required. I think we should restore the previous programming with\na separate CreateCommandTag call inside the assertion block and move this one\nback underneath the fast-path exit.\n\n\n+\t\t\t\t\tCacheInvalidateRelcacheByTuple(tuple);\n+\t\t\t}\n+\t\t\ttable_close(pg_db, RowExclusiveLock);\n+\t\t\theap_freetuple(tuple);\n+\t\t}\n+\t}\n+\tCommitTransactionCommand();\nSince we are commiting the transaction just after closing the table, is the\nrelcache invalidation going to achieve much? I guess registering the event\ndoesn't hurt much?\n\n\n+\t\t/*\n+\t\t * There can be a race condition: a login event trigger may\n+\t\t * have been added after the pg_event_trigger table was\n+\t\t * scanned, and we don't want to erroneously clear the\n+\t\t * dathasloginevt flag in this case. To be sure that this\n+\t\t * hasn't happened, repeat the scan under the pg_database\n+\t\t * table lock.\n+\t\t */\n+\t\tAcceptInvalidationMessages();\n+\t\trunlist = EventTriggerCommonSetup(NULL,\n+\t\t\t\t\t\t EVT_Login, \"login\",\n+\t\t\t\t\t\t &trigdata);\nIt seems conceptually wrong to allocate this in the TopTransactionContext when\nwe only generate the runlist to throw it away. At the very least I think we\nshould free the returned list.\n\n\n+\tif (runlist == NULL)\t/* list is still empty, so clear the\nThis should check for NIL and not NULL.\n\n\nHave you done any benchmarking on this patch? With this version I see a small\nslowdown on connection time of ~1.5% using pgbench for the case where there are\nno login event triggers defined. With a login event trigger calling an empty\nplpgsql function there is a ~30% slowdown (corresponding to ~1ms on my system).\nWhen there is a login event trigger defined all bets are off however, since the\nfunction called can be arbitrarily complex and it's up to the user to measure\nand decide - but the bare overhead we impose is still of interest of course.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Fri, 11 Mar 2022 12:22:10 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Tue, Feb 15, 2022 at 5:07 AM Greg Nancarrow <gregn4422@gmail.com> wrote:\n> I've attached a re-based version (no functional changes from the\n> previous) to fix cfbot failures.\n\nI tried this:\n\nrhaas=# create function on_login_proc() returns event_trigger as\n$$begin perform pg_sleep(10000000); end$$ language plpgsql;\nCREATE FUNCTION\nrhaas=# create event trigger on_login_trigger on login execute\nprocedure on_login_proc();\n\nWhen I then attempt to connect via psql, it hangs, as expected. When I\npress ^C, psql exits, but the backend process is not cancelled and\njust keeps chugging along in the background. The good news is that if\nI connect to another database, I can cancel all of the hung sessions\nusing pg_cancel_backend(), and all of those processes then promptly\nexit, and presumably I could accomplish the same thing by sending them\nSIGINT directly. But it's still not great behavior. It would be easy\nto use up a pile of connection slots inadvertently and have to go to\nsome trouble to get access to the server again. Since this is a psql\nbehavior and not a server behavior, one could argue that it's\nunrelated to this patch, but in practice this patch seems to increase\nthe chances of people running into problems quite a lot.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 11 Mar 2022 16:10:36 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi,\n\nOn 2022-02-15 21:07:15 +1100, Greg Nancarrow wrote:\n> Subject: [PATCH v25] Add a new \"login\" event and login event trigger support.\n> \n> The login event occurs when a user logs in to the system.\n\nI think this needs a HUGE warning in the docs about most event triggers\nneeding to check pg_is_in_recovery() or breaking hot standby. And certainly\nthe example given needs to include an pg_is_in_recovery() check.\n\n\n> + <para>\n> + The <literal>login</literal> event occurs when a user logs in to the\n> + system.\n> + Any bugs in a trigger procedure for this event may prevent successful\n> + login to the system. Such bugs may be fixed after first restarting the\n> + system in single-user mode (as event triggers are disabled in this mode).\n> + See the <xref linkend=\"app-postgres\"/> reference page for details about\n> + using single-user mode.\n> + </para>\n\nI'm strongly against adding any new dependencies on single user mode.\n\nA saner approach might be a superuser-only GUC that can be set as part of the\nconnection data (e.g. PGOPTIONS='-c ignore_login_event_trigger=true').\n\n\n> @@ -293,6 +297,27 @@ insert_event_trigger_tuple(const char *trigname, const char *eventname, Oid evtO\n> \tCatalogTupleInsert(tgrel, tuple);\n> \theap_freetuple(tuple);\n> \n> +\tif (strcmp(eventname, \"login\") == 0)\n> +\t{\n> +\t\tForm_pg_database db;\n> +\t\tRelation\tpg_db = table_open(DatabaseRelationId, RowExclusiveLock);\n> +\n> +\t\t/* Set dathasloginevt flag in pg_database */\n> +\t\ttuple = SearchSysCacheCopy1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));\n> +\t\tif (!HeapTupleIsValid(tuple))\n> +\t\t\telog(ERROR, \"cache lookup failed for database %u\", MyDatabaseId);\n> +\t\tdb = (Form_pg_database) GETSTRUCT(tuple);\n> +\t\tif (!db->dathasloginevt)\n> +\t\t{\n> +\t\t\tdb->dathasloginevt = true;\n> +\t\t\tCatalogTupleUpdate(pg_db, &tuple->t_self, tuple);\n> +\t\t}\n> +\t\telse\n> +\t\t\tCacheInvalidateRelcacheByTuple(tuple);\n> +\t\ttable_close(pg_db, RowExclusiveLock);\n> +\t\theap_freetuple(tuple);\n> +\t}\n> +\n> \t/* Depend on owner. */\n> \trecordDependencyOnOwner(EventTriggerRelationId, trigoid, evtOwner);\n\nMaybe I am confused, but isn't that CacheInvalidateRelcacheByTuple call\n*entirely* bogus? CacheInvalidateRelcacheByTuple() expects a pg_class tuple,\nbut you're passing in a pg_database tuple? And what is relcache invalidation\neven supposed to achieve here?\n\n\nI think this should mention that ->dathasloginevt is unset on login when\nappropriate.\n\n\n\n> +/*\n> + * Fire login event triggers.\n> + */\n> +void\n> +EventTriggerOnLogin(void)\n> +{\n> +\tList\t *runlist;\n> +\tEventTriggerData trigdata;\n> +\n> +\t/*\n> +\t * See EventTriggerDDLCommandStart for a discussion about why event\n> +\t * triggers are disabled in single user mode.\n> +\t */\n> +\tif (!IsUnderPostmaster || !OidIsValid(MyDatabaseId))\n> +\t\treturn;\n> +\n> +\tStartTransactionCommand();\n> +\n> +\tif (DatabaseHasLoginEventTriggers())\n> +\t{\n> +\t\trunlist = EventTriggerCommonSetup(NULL,\n> +\t\t\t\t\t\t\t\t\t\t EVT_Login, \"login\",\n> +\t\t\t\t\t\t\t\t\t\t &trigdata);\n> +\n> +\t\tif (runlist != NIL)\n> +\t\t{\n> +\t\t\t/*\n> +\t\t\t * Make sure anything the main command did will be visible to the\n> +\t\t\t * event triggers.\n> +\t\t\t */\n> +\t\t\tCommandCounterIncrement();\n\n\"Main command\"?\n\nIt's not clear to my why a CommandCounterIncrement() could be needed here -\nwhich previous writes do you need to make visible?\n\n\n\n> +\t\t\t/*\n> +\t\t\t * Runlist is empty: clear dathasloginevt flag\n> +\t\t\t */\n> +\t\t\tRelation\tpg_db = table_open(DatabaseRelationId, RowExclusiveLock);\n> +\t\t\tHeapTuple\ttuple = SearchSysCacheCopy1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));\n> +\t\t\tForm_pg_database db;\n> +\n> +\t\t\tif (!HeapTupleIsValid(tuple))\n> +\t\t\t\telog(ERROR, \"cache lookup failed for database %u\", MyDatabaseId);\n> +\n> +\t\t\tdb = (Form_pg_database) GETSTRUCT(tuple);\n> +\t\t\tif (db->dathasloginevt)\n> +\t\t\t{\n> +\t\t\t\t/*\n> +\t\t\t\t * There can be a race condition: a login event trigger may\n> +\t\t\t\t * have been added after the pg_event_trigger table was\n> +\t\t\t\t * scanned, and we don't want to erroneously clear the\n> +\t\t\t\t * dathasloginevt flag in this case. To be sure that this\n> +\t\t\t\t * hasn't happened, repeat the scan under the pg_database\n> +\t\t\t\t * table lock.\n> +\t\t\t\t */\n> +\t\t\t\tAcceptInvalidationMessages();\n> +\t\t\t\trunlist = EventTriggerCommonSetup(NULL,\n> +\t\t\t\t\t\t\t\t\t\t\t\t EVT_Login, \"login\",\n> +\t\t\t\t\t\t\t\t\t\t\t\t &trigdata);\n\nThis doesn't work. RowExclusiveLock doesn't conflict with another\nRowExclusiveLock.\n\nWhat is the AcceptInvalidationMessages() intending to do here?\n\n\n> +\t\t\t\tif (runlist == NULL)\t/* list is still empty, so clear the\n> +\t\t\t\t\t\t\t\t\t\t * flag */\n> +\t\t\t\t{\n> +\t\t\t\t\tdb->dathasloginevt = false;\n> +\t\t\t\t\tCatalogTupleUpdate(pg_db, &tuple->t_self, tuple);\n> +\t\t\t\t}\n> +\t\t\t\telse\n> +\t\t\t\t\tCacheInvalidateRelcacheByTuple(tuple);\n\nCopy of the bogus relcache stuff.\n\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 11 Mar 2022 18:46:52 -0800", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 12 Mar 2022, at 03:46, Andres Freund <andres@anarazel.de> wrote:\n\n>> + <para>\n>> + The <literal>login</literal> event occurs when a user logs in to the\n>> + system.\n>> + Any bugs in a trigger procedure for this event may prevent successful\n>> + login to the system. Such bugs may be fixed after first restarting the\n>> + system in single-user mode (as event triggers are disabled in this mode).\n>> + See the <xref linkend=\"app-postgres\"/> reference page for details about\n>> + using single-user mode.\n>> + </para>\n> \n> I'm strongly against adding any new dependencies on single user mode.\n> \n> A saner approach might be a superuser-only GUC that can be set as part of the\n> connection data (e.g. PGOPTIONS='-c ignore_login_event_trigger=true').\n\nThis, and similar approaches, has been discussed in this thread. I'm not a fan\nof holes punched with GUC's like this, but if you plan on removing single-user\nmode (as I recall seeing in an initdb thread) altogether then that kills the\ndiscussion. So.\n\nSince we already recommend single-user mode to handle broken event triggers, we\nshould IMO do something to cover all of them rather than risk ending up with\none disabling GUC per each event type. Right now we have this on the CREATE\nEVENT TRIGGER reference page:\n\n \"Event triggers are disabled in single-user mode (see postgres). If an\n erroneous event trigger disables the database so much that you can't even\n drop the trigger, restart in single-user mode and you'll be able to do\n that.\"\n\nSomething like a '-c ignore_event_trigger=<event|all>' GUC perhaps? \n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Sun, 13 Mar 2022 23:31:03 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi,\n\nOn 2022-03-13 23:31:03 +0100, Daniel Gustafsson wrote:\n> > On 12 Mar 2022, at 03:46, Andres Freund <andres@anarazel.de> wrote:\n> \n> >> + <para>\n> >> + The <literal>login</literal> event occurs when a user logs in to the\n> >> + system.\n> >> + Any bugs in a trigger procedure for this event may prevent successful\n> >> + login to the system. Such bugs may be fixed after first restarting the\n> >> + system in single-user mode (as event triggers are disabled in this mode).\n> >> + See the <xref linkend=\"app-postgres\"/> reference page for details about\n> >> + using single-user mode.\n> >> + </para>\n> > \n> > I'm strongly against adding any new dependencies on single user mode.\n> > \n> > A saner approach might be a superuser-only GUC that can be set as part of the\n> > connection data (e.g. PGOPTIONS='-c ignore_login_event_trigger=true').\n> \n> This, and similar approaches, has been discussed in this thread. I'm not a fan\n> of holes punched with GUC's like this, but if you plan on removing single-user\n> mode (as I recall seeing in an initdb thread) altogether then that kills the\n> discussion. So.\n\nEven if we end up not removing single user mode, I think it's not OK to add\nnew failure modes that require single user mode to resolve after not-absurd\noperations (I'm ok with needing single user mode if somebody does delete from\npg_authid). It's too hard to reach for most.\n\nWe already have GUCs like row_security, so it doesn't seem insane to add one\nthat disables login event triggers. What is the danger that you see?\n\n\n> Since we already recommend single-user mode to handle broken event triggers, we\n> should IMO do something to cover all of them rather than risk ending up with\n> one disabling GUC per each event type. Right now we have this on the CREATE\n> EVENT TRIGGER reference page:\n\nIMO the other types of event triggers make it a heck of a lot harder to get\nyourself into a situation that you can't get out of...\n\n\n> \"Event triggers are disabled in single-user mode (see postgres). If an\n> erroneous event trigger disables the database so much that you can't even\n> drop the trigger, restart in single-user mode and you'll be able to do\n> that.\"\n> Something like a '-c ignore_event_trigger=<event|all>' GUC perhaps? \n\nDid you mean login instead of event?\n\nSomething like it would work for me. It probably should be\nGUC_DISALLOW_IN_FILE?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Sun, 13 Mar 2022 16:33:50 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On 2022-03-13 23:31:03 +0100, Daniel Gustafsson wrote:\n>> Something like a '-c ignore_event_trigger=<event|all>' GUC perhaps? \n\n> Did you mean login instead of event?\n\n> Something like it would work for me. It probably should be\n> GUC_DISALLOW_IN_FILE?\n\nWhy? Inserting such a setting in postgresql.conf and restarting\nwould be the first thing I'd think of if I needed to get out\nof a problem. The only other way is to set it on the postmaster\ncommand line, which is going to be awkward-to-impossible with\nmost system-provided start scripts.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 13 Mar 2022 19:57:08 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi,\n\nOn 2022-03-13 19:57:08 -0400, Tom Lane wrote:\n> Andres Freund <andres@anarazel.de> writes:\n> > On 2022-03-13 23:31:03 +0100, Daniel Gustafsson wrote:\n> >> Something like a '-c ignore_event_trigger=<event|all>' GUC perhaps?\n>\n> > Did you mean login instead of event?\n>\n> > Something like it would work for me. It probably should be\n> > GUC_DISALLOW_IN_FILE?\n>\n> Why? Inserting such a setting in postgresql.conf and restarting\n> would be the first thing I'd think of if I needed to get out\n> of a problem. The only other way is to set it on the postmaster\n> command line, which is going to be awkward-to-impossible with\n> most system-provided start scripts.\n\nI was thinking that the way to use it would be to specify it as a client\noption. Like PGOPTIONS='-c ignore_event_trigger=login' psql.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Sun, 13 Mar 2022 17:08:25 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> I was thinking that the way to use it would be to specify it as a client\n> option. Like PGOPTIONS='-c ignore_event_trigger=login' psql.\n\nUgh ... that would allow people (at least superusers) to bypass\nthe login trigger at will, which seems to me to break a lot of\nthe use-cases for the feature. I supposed we'd want this to be a\nPGC_POSTMASTER setting for security reasons.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 13 Mar 2022 20:35:44 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 2022-03-13 20:35:44 -0400, Tom Lane wrote:\n> Andres Freund <andres@anarazel.de> writes:\n> > I was thinking that the way to use it would be to specify it as a client\n> > option. Like PGOPTIONS='-c ignore_event_trigger=login' psql.\n> \n> Ugh ... that would allow people (at least superusers) to bypass\n> the login trigger at will, which seems to me to break a lot of\n> the use-cases for the feature. I supposed we'd want this to be a\n> PGC_POSTMASTER setting for security reasons.\n\nShrug. This doesn't seem to add actual security to me.\n\n\n", "msg_date": "Sun, 13 Mar 2022 19:17:10 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 14 Mar 2022, at 00:33, Andres Freund <andres@anarazel.de> wrote:\n\n> We already have GUCs like row_security, so it doesn't seem insane to add one\n> that disables login event triggers. What is the danger that you see?\n\nMy fear is that GUCs like that end up as permanent fixtures in scripts etc\nafter having been used temporary, and then X timeunits later someone realize\nthat the backup has never actually really worked due to a subtle issue, or\nsomething else unpleasant.\n\nThe row_security GUC is kind of different IMO, as it's required for pg_dump\n(though it can be used in the same way as the above).\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Mon, 14 Mar 2022 09:50:25 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Sun, Mar 13, 2022 at 7:34 PM Andres Freund <andres@anarazel.de> wrote:\n> IMO the other types of event triggers make it a heck of a lot harder to get\n> yourself into a situation that you can't get out of...\n\nIn particular, unless something has changed since I committed this\nstuff originally, there's no existing type of event trigger than can\nprevent the superuser from logging in and running DROP EVENT TRIGGER\n-- or a SELECT on the system catalogs to find out what to drop. That\nwas very much a deliberate decision on my part.\n\nI think it's fine to require dropping to single-user mode as a way of\nrecovering from extreme situations where, for example, there are\ncorrupted database files. If we don't need it even then, cool, but if\nwe do, I'm not sad. But all we're talking about here is somebody maybe\nrunning a command that perhaps they should not have run. Having to\ntake the whole system down to recover from that seems excessively\npainful.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 14 Mar 2022 09:18:42 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 14 Mar 2022, at 01:08, Andres Freund <andres@anarazel.de> wrote:\n\n> I was thinking that the way to use it would be to specify it as a client\n> option. Like PGOPTIONS='-c ignore_event_trigger=login' psql.\n\nAttached is a quick PoC/sketch of such a patch, where 0001 adds a guc, 0002 is\nthe previously posted v25 login event trigger patch, and 0003 adapts is to\nallow ignoring it (0002/0003 split only for illustrative purposes of course).\nIs this along the lines of what you were thinking?\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/", "msg_date": "Mon, 14 Mar 2022 14:47:09 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi,\n\nOn 2022-03-14 14:47:09 +0100, Daniel Gustafsson wrote:\n> > On 14 Mar 2022, at 01:08, Andres Freund <andres@anarazel.de> wrote:\n> \n> > I was thinking that the way to use it would be to specify it as a client\n> > option. Like PGOPTIONS='-c ignore_event_trigger=login' psql.\n> \n> Attached is a quick PoC/sketch of such a patch, where 0001 adds a guc, 0002 is\n> the previously posted v25 login event trigger patch, and 0003 adapts is to\n> allow ignoring it (0002/0003 split only for illustrative purposes of course).\n> Is this along the lines of what you were thinking?\n\nYes.\n\nOf course there's still the bogus cache invalidation stuff etc that I\ncommented on upthread.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 14 Mar 2022 09:10:49 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 14 Mar 2022, at 17:10, Andres Freund <andres@anarazel.de> wrote:\n> \n> Hi,\n> \n> On 2022-03-14 14:47:09 +0100, Daniel Gustafsson wrote:\n>>> On 14 Mar 2022, at 01:08, Andres Freund <andres@anarazel.de> wrote:\n>> \n>>> I was thinking that the way to use it would be to specify it as a client\n>>> option. Like PGOPTIONS='-c ignore_event_trigger=login' psql.\n>> \n>> Attached is a quick PoC/sketch of such a patch, where 0001 adds a guc, 0002 is\n>> the previously posted v25 login event trigger patch, and 0003 adapts is to\n>> allow ignoring it (0002/0003 split only for illustrative purposes of course).\n>> Is this along the lines of what you were thinking?\n> \n> Yes.\n> \n> Of course there's still the bogus cache invalidation stuff etc that I\n> commented on upthread.\n\nYeah, that was the previously posted v25 from the author (who adopted it from\nthe original author). I took the liberty to quickly poke at the review\ncomments you had left as well as the ones that I had found to try and progress\nthe patch. 0001 should really go in it's own thread though to not hide it from\nanyone interested who isn't looking at this thread.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/", "msg_date": "Tue, 15 Mar 2022 21:52:43 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Daniel Gustafsson писал 2022-03-15 23:52:\n\n> Yeah, that was the previously posted v25 from the author (who adopted \n> it from\n> the original author). I took the liberty to quickly poke at the review\n> comments you had left as well as the ones that I had found to try and \n> progress\n> the patch. 0001 should really go in it's own thread though to not hide \n> it from\n> anyone interested who isn't looking at this thread.\nHi\nI got an error while running tests on Windows:\n2022-03-17 17:30:02.458 MSK [6920] [unknown] LOG: no match in usermap \n\"regress\" for user \"regress_user\" authenticated as \n\"vagrant@WINDOWS-2019\"\n2022-03-17 17:30:02.458 MSK [6920] [unknown] FATAL: SSPI authentication \nfailed for user \"regress_user\"\n2022-03-17 17:30:02.458 MSK [6920] [unknown] DETAIL: Connection matched \npg_hba.conf line 2: \"host all all 127.0.0.1/32 sspi include_realm=1 \nmap=regress\"\n2022-03-17 17:30:02.526 MSK [3432] FATAL: could not receive data from \nWAL stream: server closed the connection unexpectedly\n\t\tThis probably means the server terminated abnormally\n\t\tbefore or while processing the request.\n\nI propose to make such correction:\n--- a/src/test/recovery/t/001_stream_rep.pl\n+++ b/src/test/recovery/t/001_stream_rep.pl\n@@ -14,7 +14,7 @@ my $node_primary = get_new_node('primary');\n # and it needs proper authentication configuration.\n $node_primary->init(\n allows_streaming => 1,\n- auth_extra => [ '--create-role', 'repl_role' ]);\n+ auth_extra => [ '--create-role', 'repl_role,regress_user' \n]);\n $node_primary->start;\n my $backup_name = 'my_backup';\n\n\n-- \nAndrey Sokolov\nPostgres Professional: http://www.postgrespro.com\n\n\n", "msg_date": "Fri, 18 Mar 2022 10:24:46 +0300", "msg_from": "a.sokolov@postgrespro.ru", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 18 Mar 2022, at 08:24, a.sokolov@postgrespro.ru wrote:\n\n> - auth_extra => [ '--create-role', 'repl_role' ]);\n> + auth_extra => [ '--create-role', 'repl_role,regress_user' ]);\n\nLooking at the test in question it's not entirely clear to me what the original\nauthor really intended here, so I've changed it up a bit to actually test\nsomething and removed the need for the regress_user role. I've also fixed the\nsilly mistake highlighted in the postgresql.conf.sample test.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/", "msg_date": "Fri, 18 Mar 2022 17:03:39 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi,\n\nOn 2022-03-18 17:03:39 +0100, Daniel Gustafsson wrote:\n> > On 18 Mar 2022, at 08:24, a.sokolov@postgrespro.ru wrote:\n> \n> > - auth_extra => [ '--create-role', 'repl_role' ]);\n> > + auth_extra => [ '--create-role', 'repl_role,regress_user' ]);\n> \n> Looking at the test in question it's not entirely clear to me what the original\n> author really intended here, so I've changed it up a bit to actually test\n> something and removed the need for the regress_user role. I've also fixed the\n> silly mistake highlighted in the postgresql.conf.sample test.\n\ndocs fail to build: https://cirrus-ci.com/task/5556234047717376?logs=docs_build#L349\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 21 Mar 2022 19:48:44 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 22 Mar 2022, at 04:48, Andres Freund <andres@anarazel.de> wrote:\n\n> docs fail to build: https://cirrus-ci.com/task/5556234047717376?logs=docs_build#L349\n\nUgh, that one was on me and not the original author. Fixed.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/", "msg_date": "Tue, 22 Mar 2022 10:43:51 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Daniel Gustafsson писал 2022-03-22 11:43:\n>> On 22 Mar 2022, at 04:48, Andres Freund <andres@anarazel.de> wrote:\n> \n>> docs fail to build: \n>> https://cirrus-ci.com/task/5556234047717376?logs=docs_build#L349\n> \n> Ugh, that one was on me and not the original author. Fixed.\n> \n\n+ data initialization. It is vital that any event trigger using the\n+ <literal>login</literal> event checks whether or not the database \nis in\n+ recovery.\n\nDoes any trigger really have to contain a pg_is_in_recovery() call? In \nthis message \n(https://www.postgresql.org/message-id/20220312024652.lvgehszwke4hhove%40alap3.anarazel.de) \nit was only about triggers on hot standby, which run not read-only \nqueries\n\n-- \nAndrey Sokolov\nPostgres Professional: http://www.postgrespro.com\n\n\n", "msg_date": "Mon, 28 Mar 2022 15:57:37 +0300", "msg_from": "a.sokolov@postgrespro.ru", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi,\n\nOn 2022-03-28 15:57:37 +0300, a.sokolov@postgrespro.ru wrote:\n> + data initialization. It is vital that any event trigger using the\n> + <literal>login</literal> event checks whether or not the database is in\n> + recovery.\n> \n> Does any trigger really have to contain a pg_is_in_recovery() call?\n\nNot *any* trigger, just any trigger that writes.\n\n\n> In this message\n> (https://www.postgresql.org/message-id/20220312024652.lvgehszwke4hhove%40alap3.anarazel.de)\n> it was only about triggers on hot standby, which run not read-only queries\n\nThe problem precisely is that the login triggers run on hot standby nodes, and\nthat if they do writes, you can't login anymore.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 28 Mar 2022 10:10:26 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 28 Mar 2022, at 19:10, Andres Freund <andres@anarazel.de> wrote:\n> On 2022-03-28 15:57:37 +0300, a.sokolov@postgrespro.ru wrote:\n\n>> + data initialization. It is vital that any event trigger using the\n>> + <literal>login</literal> event checks whether or not the database is in\n>> + recovery.\n>> \n>> Does any trigger really have to contain a pg_is_in_recovery() call?\n> \n> Not *any* trigger, just any trigger that writes.\n\nThats correct, the docs should be updated with something like the below I\nreckon.\n\n It is vital that event trigger using the <literal>login</literal> event\n which has side-effects checks whether or not the database is in recovery to\n ensure they are not performing modifications to hot standby nodes.\n\n>> In this message\n>> (https://www.postgresql.org/message-id/20220312024652.lvgehszwke4hhove%40alap3.anarazel.de)\n>> it was only about triggers on hot standby, which run not read-only queries\n> \n> The problem precisely is that the login triggers run on hot standby nodes, and\n> that if they do writes, you can't login anymore.\n\nDo you think this potential foot-gun is scary enough to reject this patch?\nThere are lots of creative ways to cause Nagios alerts from ones database, but\nthis has the potential to do so with a small bug in userland code. Still, I\nkind of like the feature so I'm indecisive.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Mon, 28 Mar 2022 23:27:56 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi,\n\nOn 2022-03-28 23:27:56 +0200, Daniel Gustafsson wrote:\n> > On 28 Mar 2022, at 19:10, Andres Freund <andres@anarazel.de> wrote:\n> > On 2022-03-28 15:57:37 +0300, a.sokolov@postgrespro.ru wrote:\n> \n> >> + data initialization. It is vital that any event trigger using the\n> >> + <literal>login</literal> event checks whether or not the database is in\n> >> + recovery.\n> >> \n> >> Does any trigger really have to contain a pg_is_in_recovery() call?\n> > \n> > Not *any* trigger, just any trigger that writes.\n> \n> Thats correct, the docs should be updated with something like the below I\n> reckon.\n> \n> It is vital that event trigger using the <literal>login</literal> event\n> which has side-effects checks whether or not the database is in recovery to\n> ensure they are not performing modifications to hot standby nodes.\n\nMaybe side-effects is a bit too general? Emitting a log message, rejecting a\nlogin, setting some GUCs, etc are all side-effects too.\n\n\n> >> In this message\n> >> (https://www.postgresql.org/message-id/20220312024652.lvgehszwke4hhove%40alap3.anarazel.de)\n> >> it was only about triggers on hot standby, which run not read-only queries\n> > \n> > The problem precisely is that the login triggers run on hot standby nodes, and\n> > that if they do writes, you can't login anymore.\n> \n> Do you think this potential foot-gun is scary enough to reject this patch?\n> There are lots of creative ways to cause Nagios alerts from ones database, but\n> this has the potential to do so with a small bug in userland code. Still, I\n> kind of like the feature so I'm indecisive.\n\nIt does seem like a huge footgun. But also kinda useful. So I'm really +-0.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 28 Mar 2022 14:31:25 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 28 Mar 2022, at 23:31, Andres Freund <andres@anarazel.de> wrote:\n> \n> Hi,\n> \n> On 2022-03-28 23:27:56 +0200, Daniel Gustafsson wrote:\n>>> On 28 Mar 2022, at 19:10, Andres Freund <andres@anarazel.de> wrote:\n>>> On 2022-03-28 15:57:37 +0300, a.sokolov@postgrespro.ru wrote:\n>> \n>>>> + data initialization. It is vital that any event trigger using the\n>>>> + <literal>login</literal> event checks whether or not the database is in\n>>>> + recovery.\n>>>> \n>>>> Does any trigger really have to contain a pg_is_in_recovery() call?\n>>> \n>>> Not *any* trigger, just any trigger that writes.\n>> \n>> Thats correct, the docs should be updated with something like the below I\n>> reckon.\n>> \n>> It is vital that event trigger using the <literal>login</literal> event\n>> which has side-effects checks whether or not the database is in recovery to\n>> ensure they are not performing modifications to hot standby nodes.\n> \n> Maybe side-effects is a bit too general? Emitting a log message, rejecting a\n> login, setting some GUCs, etc are all side-effects too.\n\nGood point, it needs to say that modifications that cause WAL to be generated\nare prohibited, but in a more user-friendly readable way. Perhaps in a big red\nwarning box.\n\n>>>> In this message\n>>>> (https://www.postgresql.org/message-id/20220312024652.lvgehszwke4hhove%40alap3.anarazel.de)\n>>>> it was only about triggers on hot standby, which run not read-only queries\n>>> \n>>> The problem precisely is that the login triggers run on hot standby nodes, and\n>>> that if they do writes, you can't login anymore.\n>> \n>> Do you think this potential foot-gun is scary enough to reject this patch?\n>> There are lots of creative ways to cause Nagios alerts from ones database, but\n>> this has the potential to do so with a small bug in userland code. Still, I\n>> kind of like the feature so I'm indecisive.\n> \n> It does seem like a huge footgun. But also kinda useful. So I'm really +-0.\n\nLooks like we are in agreement here. I'm going to go over it again and sleep\non it some more before the deadline hits.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Mon, 28 Mar 2022 23:36:39 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On 2022-03-28 23:27:56 +0200, Daniel Gustafsson wrote:\n>> Do you think this potential foot-gun is scary enough to reject this patch?\n>> There are lots of creative ways to cause Nagios alerts from ones database, but\n>> this has the potential to do so with a small bug in userland code. Still, I\n>> kind of like the feature so I'm indecisive.\n\n> It does seem like a huge footgun. But also kinda useful. So I'm really +-0.\n\nAn on-login trigger is *necessarily* a foot-gun; I don't see that this\nparticular failure mode makes it any worse than it would be anyway.\nThere has to be some not-too-difficult-to-use way to bypass a broken\nlogin trigger. Assuming we are happy with the design for doing that,\nmight as well accept the hazards.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 28 Mar 2022 18:40:47 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi, \n>Tue, March 29, 2022, 0:31 +03:00 from Andres Freund <andres@anarazel.de>:\n> \n>Hi,\n>\n>On 2022-03-28 23:27:56 +0200, Daniel Gustafsson wrote:\n>> > On 28 Mar 2022, at 19:10, Andres Freund < andres@anarazel.de > wrote:\n>> > On 2022-03-28 15:57:37 +0300, a.sokolov@postgrespro.ru wrote:\n>>\n>> >> + data initialization. It is vital that any event trigger using the\n>> >> + <literal>login</literal> event checks whether or not the database is in\n>> >> + recovery.\n>> »\n \n>> >> Does any trigger really have to contain a pg_is_in_recovery() call?\n>> >\n>> > Not *any* trigger, just any trigger that writes.\n>>\n>> Thats correct, the docs should be updated with something like the below I\n>> reckon.\n>>\n>> It is vital that event trigger using the <literal>login</literal> event\n>> which has side-effects checks whether or not the database is in recovery to\n>> ensure they are not performing modifications to hot standby nodes.\n>\n>Maybe side-effects is a bit too general? Emitting a log message, rejecting a\n>login, setting some GUCs, etc are all side-effects too.\nSomething like this:\n \n<important>\n    <para>\n      The <literal>login</literal> triggers fire also on standby servers.\n      To keep them from becoming inaccessible, such triggers should\n      avoid writing anything to the database when running on a standby.\n      This can be achieved by checking <function>pg_is_in_recovery</function>(), see an example below.\n    </para>\n</important>\n> \nAlso, please fix a typo in doc/src/sgml/ref/create_event_trigger.sgml :\n \n- single-user mode and you'll be able to do that. Even triggers can also be\n+ single-user mode and you'll be able to do that. Event triggers can also be\n \nRegarding the trigger function example:\nIt does not do anything if run on a standby. To show that it can do something on a standby to, I propose to move throwing the night exception to the beginning.\nSo it will be:\n \nCREATE OR REPLACE FUNCTION init_session() \nRETURNS event_trigger SECURITY DEFINER LANGUAGE plpgsql AS \n$$ \nDECLARE \n hour integer = EXTRACT('hour' FROM current_time); \n rec boolean;\nBEGIN\n\n-- 1) Forbid logging in late:\nIF hour BETWEEN 2 AND 4 THEN\n RAISE EXCEPTION 'Login forbidden'; -- do not allow to login these hours\nEND IF;\n\n-- The remaining stuff cannot be done on standbys,\n-- so ensure the database is not in recovery\nSELECT pg_is_in_recovery() INTO rec;\nIF rec THEN\n RETURN;\nEND IF\n\n-- 2) Assign some roles\n\nIF hour BETWEEN 8 AND 20 THEN -- at daytime grant the day_worker role\n EXECUTE 'REVOKE night_worker FROM ' || quote_ident(session_user);\n EXECUTE 'GRANT day_worker TO ' || quote_ident(session_user);\nELSE -- at other time grant the night_worker role\n EXECUTE 'REVOKE day_worker FROM ' || quote_ident(session_user);\n EXECUTE 'GRANT night_worker TO ' || quote_ident(session_user);\nEND IF;\n\n-- 3) Initialize some user session data\n\nCREATE TEMP TABLE session_storage (x float, y integer);\n\n-- 4) Log the connection time\n\nINSERT INTO user_login_log VALUES (session_user, current_timestamp);\n\nEND;\n$$;\nFinally, let me propose to append to the regression test the following:\n \n \n\\c \nSELECT dathasloginevt FROM pg_database WHERE datname= :'DBNAME';\n \nwhich should output:\n dathasloginevt \n----------------\n f\n(1 row)\n \nSo we can check that removal of the event trigger resets this flag in pg_database. Note that reconnect (\\c) is necessary here.\n \nRegards,\nIvan\n \n>\n>> >> In this message\n>> >> ( https://www.postgresql.org/message-id/20220312024652.lvgehszwke4hhove%40alap3.anarazel.de )\n>> >> it was only about triggers on hot standby, which run not read-only queries\n>> >\n>> > The problem precisely is that the login triggers run on hot standby nodes, and\n>> > that if they do writes, you can't login anymore.\n>>\n>> Do you think this potential foot-gun is scary enough to reject this patch?\n>> There are lots of creative ways to cause Nagios alerts from ones database, but\n>> this has the potential to do so with a small bug in userland code. Still, I\n>> kind of like the feature so I'm indecisive.\n>\n>It does seem like a huge footgun. But also kinda useful. So I'm really +-0.\n>\n>Greetings,\n>\n>Andres Freund\n \n Hi,Tue, March 29, 2022, 0:31 +03:00 from Andres Freund <andres@anarazel.de>: Hi,On 2022-03-28 23:27:56 +0200, Daniel Gustafsson wrote:> > On 28 Mar 2022, at 19:10, Andres Freund <andres@anarazel.de> wrote:> > On 2022-03-28 15:57:37 +0300, a.sokolov@postgrespro.ru wrote:>> >> + data initialization. It is vital that any event trigger using the> >> + <literal>login</literal> event checks whether or not the database is in> >> + recovery.> » > >> Does any trigger really have to contain a pg_is_in_recovery() call?> >> > Not *any* trigger, just any trigger that writes.>> Thats correct, the docs should be updated with something like the below I> reckon.>> It is vital that event trigger using the <literal>login</literal> event> which has side-effects checks whether or not the database is in recovery to> ensure they are not performing modifications to hot standby nodes.Maybe side-effects is a bit too general? Emitting a log message, rejecting alogin, setting some GUCs, etc are all side-effects too.Something like this: <important>    <para>      The <literal>login</literal> triggers fire also on standby servers.      To keep them from becoming inaccessible, such triggers should      avoid writing anything to the database when running on a standby.      This can be achieved by checking <function>pg_is_in_recovery</function>(), see an example below.    </para></important> Also, please fix a typo in doc/src/sgml/ref/create_event_trigger.sgml : - single-user mode and you'll be able to do that. Even triggers can also be\n+ single-user mode and you'll be able to do that. Event triggers can also be Regarding the trigger function example:It does not do anything if run on a standby. To show that it can do something on a standby to, I propose to move throwing the night exception to the beginning.So it will be: CREATE OR REPLACE FUNCTION init_session() \nRETURNS event_trigger SECURITY DEFINER LANGUAGE plpgsql AS \n$$ \nDECLARE \n hour integer = EXTRACT('hour' FROM current_time); \n rec boolean;\nBEGIN\n\n-- 1) Forbid logging in late:\nIF hour BETWEEN 2 AND 4 THEN\n RAISE EXCEPTION 'Login forbidden'; -- do not allow to login these hours\nEND IF;\n\n-- The remaining stuff cannot be done on standbys,\n-- so ensure the database is not in recovery\nSELECT pg_is_in_recovery() INTO rec;\nIF rec THEN\n RETURN;\nEND IF\n\n-- 2) Assign some roles\n\nIF hour BETWEEN 8 AND 20 THEN -- at daytime grant the day_worker role\n EXECUTE 'REVOKE night_worker FROM ' || quote_ident(session_user);\n EXECUTE 'GRANT day_worker TO ' || quote_ident(session_user);\nELSE -- at other time grant the night_worker role\n EXECUTE 'REVOKE day_worker FROM ' || quote_ident(session_user);\n EXECUTE 'GRANT night_worker TO ' || quote_ident(session_user);\nEND IF;\n\n-- 3) Initialize some user session data\n\nCREATE TEMP TABLE session_storage (x float, y integer);\n\n-- 4) Log the connection time\n\nINSERT INTO user_login_log VALUES (session_user, current_timestamp);\n\nEND;\n$$;Finally, let me propose to append to the regression test the following:  \\c \nSELECT dathasloginevt FROM pg_database WHERE datname= :'DBNAME'; which should output: dathasloginevt \n----------------\n f\n(1 row) So we can check that removal of the event trigger resets this flag in pg_database. Note that reconnect (\\c) is necessary here. Regards,Ivan > >> In this message> >> (https://www.postgresql.org/message-id/20220312024652.lvgehszwke4hhove%40alap3.anarazel.de)> >> it was only about triggers on hot standby, which run not read-only queries> >> > The problem precisely is that the login triggers run on hot standby nodes, and> > that if they do writes, you can't login anymore.>> Do you think this potential foot-gun is scary enough to reject this patch?> There are lots of creative ways to cause Nagios alerts from ones database, but> this has the potential to do so with a small bug in userland code. Still, I> kind of like the feature so I'm indecisive.It does seem like a huge footgun. But also kinda useful. So I'm really +-0.Greetings,Andres Freund", "msg_date": "Wed, 30 Mar 2022 14:21:28 +0300", "msg_from": "=?UTF-8?B?SXZhbiBQYW5jaGVua28=?= <wao@mail.ru>", "msg_from_op": false, "msg_subject": "=?UTF-8?B?UmVbMl06IE9uIGxvZ2luIHRyaWdnZXI6IHRha2UgdGhyZWU=?=" }, { "msg_contents": "> On 30 Mar 2022, at 13:21, Ivan Panchenko <wao@mail.ru> wrote:\n> Maybe side-effects is a bit too general? Emitting a log message, rejecting a\n> login, setting some GUCs, etc are all side-effects too.\n> Something like this:\n\nI've reworded the docs close to what you suggested here.\n\n> Also, please fix a typo in doc/src/sgml/ref/create_event_trigger.sgml :\n\nDone.\n\n> Regarding the trigger function example:\n> It does not do anything if run on a standby. To show that it can do something on a standby to, I propose to move throwing the night exception to the beginning.\n\nGood idea, done.\n\n> Finally, let me propose to append to the regression test the following:\n\nAlso a good idea, done.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/", "msg_date": "Wed, 30 Mar 2022 15:48:46 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 29 Mar 2022, at 00:40, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> Andres Freund <andres@anarazel.de> writes:\n>> On 2022-03-28 23:27:56 +0200, Daniel Gustafsson wrote:\n>>> Do you think this potential foot-gun is scary enough to reject this patch?\n>>> There are lots of creative ways to cause Nagios alerts from ones database, but\n>>> this has the potential to do so with a small bug in userland code. Still, I\n>>> kind of like the feature so I'm indecisive.\n> \n>> It does seem like a huge footgun. But also kinda useful. So I'm really +-0.\n> \n> An on-login trigger is *necessarily* a foot-gun; I don't see that this\n> particular failure mode makes it any worse than it would be anyway.\n\nAgreed.\n\n> There has to be some not-too-difficult-to-use way to bypass a broken\n> login trigger. Assuming we are happy with the design for doing that,\n> might as well accept the hazards.\n\nThe GUC in this patchset seems to be in line with what most in this thread have\npreferred, and with that in place (and single-user mode which still works for\nthis) I think we have that covered.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Wed, 30 Mar 2022 15:51:18 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Daniel Gustafsson писал 2022-03-30 16:48:\n>> On 30 Mar 2022, at 13:21, Ivan Panchenko <wao@mail.ru> wrote:\n>> Maybe side-effects is a bit too general? Emitting a log message, \n>> rejecting a\n>> login, setting some GUCs, etc are all side-effects too.\n>> Something like this:\n> \n> I've reworded the docs close to what you suggested here.\n> \n>> Also, please fix a typo in doc/src/sgml/ref/create_event_trigger.sgml \n>> :\n> \n> Done.\n> \n>> Regarding the trigger function example:\n>> It does not do anything if run on a standby. To show that it can do \n>> something on a standby to, I propose to move throwing the night \n>> exception to the beginning.\n> \n> Good idea, done.\n> \n>> Finally, let me propose to append to the regression test the \n>> following:\n> \n> Also a good idea, done.\n> \n> --\n> Daniel Gustafsson\t\thttps://vmware.com/\n\nPlease fix a typo in doc/src/sgml/event-trigger.sgml: \"precvent\"\n\n-- \nAndrey Sokolov\nPostgres Professional: http://www.postgrespro.com\n\n\n", "msg_date": "Fri, 01 Apr 2022 10:16:04 +0300", "msg_from": "a.sokolov@postgrespro.ru", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 1 Apr 2022, at 09:16, a.sokolov@postgrespro.ru wrote:\n\n> Please fix a typo in doc/src/sgml/event-trigger.sgml: \"precvent\"\n\nWill do. With that fixed I think this is ready and unless I find something on\nanother read through and test pass I hope to be able to push this before the CF\ncloses today.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Thu, 7 Apr 2022 12:06:38 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "This had bitrotted a fair bit, attached is a rebase along with (mostly)\ndocumentation fixes. 0001 adds a generic GUC for ignoring event triggers and\n0002 adds the login event with event trigger support, and hooks it up to the\nGUC such that broken triggers wont require single-user mode. Moving the CF\nentry back to Needs Review.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/", "msg_date": "Fri, 2 Sep 2022 17:36:55 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Fri, Sep 2, 2022 at 8:37 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n\n> This had bitrotted a fair bit, attached is a rebase along with (mostly)\n> documentation fixes. 0001 adds a generic GUC for ignoring event triggers\n> and\n> 0002 adds the login event with event trigger support, and hooks it up to\n> the\n> GUC such that broken triggers wont require single-user mode. Moving the CF\n> entry back to Needs Review.\n>\n> --\n> Daniel Gustafsson https://vmware.com/\n>\n> Hi,\nFor EventTriggerOnLogin():\n\n+ LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,\nAccessExclusiveLock);\n+\n+ tuple = SearchSysCacheCopy1(DATABASEOID,\nObjectIdGetDatum(MyDatabaseId));\n+\n+ if (!HeapTupleIsValid(tuple))\n+ elog(ERROR, \"cache lookup failed for database %u\",\nMyDatabaseId);\n\nShould the lock be taken after the check (HeapTupleIsValid) is done ?\n\nCheers\n\nOn Fri, Sep 2, 2022 at 8:37 AM Daniel Gustafsson <daniel@yesql.se> wrote:This had bitrotted a fair bit, attached is a rebase along with (mostly)\ndocumentation fixes.  0001 adds a generic GUC for ignoring event triggers and\n0002 adds the login event with event trigger support, and hooks it up to the\nGUC such that broken triggers wont require single-user mode.  Moving the CF\nentry back to Needs Review.\n\n--\nDaniel Gustafsson               https://vmware.com/\nHi,For EventTriggerOnLogin():+           LockSharedObject(DatabaseRelationId, MyDatabaseId, 0, AccessExclusiveLock);++           tuple = SearchSysCacheCopy1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));++           if (!HeapTupleIsValid(tuple))+               elog(ERROR, \"cache lookup failed for database %u\", MyDatabaseId);Should the lock be taken after the check (HeapTupleIsValid) is done ?Cheers", "msg_date": "Fri, 2 Sep 2022 09:13:39 -0700", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 02.09.2022 18:36, Daniel Gustafsson wrote:\n> This had bitrotted a fair bit, attached is a rebase along with (mostly)\n> documentation fixes. 0001 adds a generic GUC for ignoring event triggers and\n> 0002 adds the login event with event trigger support, and hooks it up to the\n> GUC such that broken triggers wont require single-user mode. Moving the CF\n> entry back to Needs Review.\n\n\nHello!\n\nThere is a race around setting and clearing of dathasloginevt.\n\nSteps to reproduce:\n\n1. Create a trigger:\n\n CREATE FUNCTION on_login_proc() RETURNS event_trigger AS $$\n BEGIN\n RAISE NOTICE 'You are welcome!';\n END;\n $$ LANGUAGE plpgsql;\n\n CREATE EVENT TRIGGER on_login_trigger ON login EXECUTE PROCEDURE \non_login_proc();\n\n2. Then drop it, but don't start new sessions:\n\n DROP EVENT TRIGGER on_login_trigger;\n\n3. Create another trigger, but don't commit yet:\n\n BEGIN;\n CREATE EVENT TRIGGER on_login_trigger ON login EXECUTE PROCEDURE \non_login_proc();\n\n4. Start a new session. This clears dathasloginevt.\n\n5. Commit the transaction:\n\n COMMIT;\n\nNow we have a trigger, but it doesn't fire, because dathasloginevt=false.\n\n\nIf two sessions create triggers concurrently, one of them will fail.\n\nSteps:\n\n1. In the first session, start a transaction and create a trigger:\n\n BEGIN;\n CREATE EVENT TRIGGER on_login_trigger1 ON login EXECUTE PROCEDURE \non_login_proc();\n\n2. In the second session, create another trigger (this query blocks):\n\n CREATE EVENT TRIGGER on_login_trigger2 ON login EXECUTE PROCEDURE \non_login_proc();\n\n3. Commit in the first session:\n\n COMMIT;\n\nThe second session fails:\n\n postgres=# CREATE EVENT TRIGGER on_login_trigger2 ON login EXECUTE \nPROCEDURE on_login_proc();\n ERROR: tuple concurrently updated\n\n\n\nWhat else bothers me is that login triggers execute in an environment \nunder user control and one has to be very careful. The example trigger \nfrom the documentation\n\n+DECLARE\n\n+ hour integer = EXTRACT('hour' FROM current_time);\n\n+ rec boolean;\n\n+BEGIN\n\n+-- 1. Forbid logging in between 2AM and 4AM.\n\n+IF hour BETWEEN 2 AND 4 THEN\n\n+ RAISE EXCEPTION 'Login forbidden';\n\n+END IF;\n\n\ncan be bypassed with PGOPTIONS='-c timezone=...'. Probably this is \nnothing new and concerns any SECURITY DEFINER function, but still...\n\n\nBest regards,\n\n-- \nSergey Shinderuk\t\thttps://postgrespro.com/\n\n\n", "msg_date": "Tue, 20 Sep 2022 16:43:59 +0300", "msg_from": "Sergey Shinderuk <s.shinderuk@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 20 Sep 2022, at 15:43, Sergey Shinderuk <s.shinderuk@postgrespro.ru> wrote:\n> \n> On 02.09.2022 18:36, Daniel Gustafsson wrote:\n>> This had bitrotted a fair bit, attached is a rebase along with (mostly)\n>> documentation fixes. 0001 adds a generic GUC for ignoring event triggers and\n>> 0002 adds the login event with event trigger support, and hooks it up to the\n>> GUC such that broken triggers wont require single-user mode. Moving the CF\n>> entry back to Needs Review.\n\n> There is a race around setting and clearing of dathasloginevt.\n\nThanks for the report! The whole dathasloginevt mechanism is IMO too clunky\nand unelegant to go ahead with, I wouldn't be surprised if there are other bugs\nlurking there. Since the original authors seems to have retired from the patch\n(I've only rebased it to try and help) I am inclined to mark it as returned\nwith feedback.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Tue, 20 Sep 2022 16:10:22 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 20.09.2022 17:10, Daniel Gustafsson wrote:\n>> On 20 Sep 2022, at 15:43, Sergey Shinderuk <s.shinderuk@postgrespro.ru> wrote: \n>> There is a race around setting and clearing of dathasloginevt.\n> \n> Thanks for the report! The whole dathasloginevt mechanism is IMO too clunky\n> and unelegant to go ahead with, I wouldn't be surprised if there are other bugs\n> lurking there.\nIndeed.\n\nCREATE DATABASE doesn't copy dathasloginevt from the template database.\nALTER EVENT TRIGGER ... ENABLE doesn't set dathasloginevt.\n\nIn both cases triggers are enabled according to \\dy output, but don't \nfire. The admin may not notice it immediately.\n\n-- \nSergey Shinderuk\t\thttps://postgrespro.com/\n\n\n", "msg_date": "Wed, 21 Sep 2022 16:29:12 +0300", "msg_from": "Sergey Shinderuk <s.shinderuk@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 20 Sep 2022, at 16:10, Daniel Gustafsson <daniel@yesql.se> wrote:\n\n> Since the original authors seems to have retired from the patch\n> (I've only rebased it to try and help) I am inclined to mark it as returned\n> with feedback.\n\nDoing so now since no updates have been posted for quite some time and holes\nhave been poked in the patch.\n\nThe GUC for temporarily disabling event triggers, to avoid the need for single-\nuser mode during troubleshooting, might however be of interest so I will break\nthat out and post to a new thread.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Thu, 3 Nov 2022 21:23:01 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "2022年11月4日(金) 5:23 Daniel Gustafsson <daniel@yesql.se>:\n>\n> > On 20 Sep 2022, at 16:10, Daniel Gustafsson <daniel@yesql.se> wrote:\n>\n> > Since the original authors seems to have retired from the patch\n> > (I've only rebased it to try and help) I am inclined to mark it as returned\n> > with feedback.\n>\n> Doing so now since no updates have been posted for quite some time and holes\n> have been poked in the patch.\n\nI see it was still \"Waiting on Author\" so I went ahead and changed the status.\n\n> The GUC for temporarily disabling event triggers, to avoid the need for single-\n> user mode during troubleshooting, might however be of interest so I will break\n> that out and post to a new thread.\n\nFor reference this is the new thread:\n\n https://www.postgresql.org/message-id/9140106E-F9BF-4D85-8FC8-F2D3C094A6D9%40yesql.se\n\nRegards\n\nIan Barwick\n\n\n", "msg_date": "Fri, 4 Nov 2022 09:58:23 +0900", "msg_from": "Ian Lawrence Barwick <barwick@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi hackers,\n\n\n\nSince the original authors, as Daniel said, seems to have retired from the\npatch, I have allowed myself to continue the patch polishing.\n\nAttached v32 includes fresh rebase and the following fixes:\n\n- Copying dathasloginevt flag during DB creation from template;\n\n- Restoring dathasloginevt flag after re-enabling a disabled trigger;\n\n- Preserving dathasloginevt flag during not-running a trigger because of\nsome filters (running with 'session_replication_role=replica' for example);\n\n- Checking tags during the trigger creation;\n\nThe (en/dis)abling GUC was removed from the patch by default because it is\nnow discussed and supported in a separate thread by Daniel Gustaffson:\n\n\n*https://www.postgresql.org/message-id/9140106E-F9BF-4D85-8FC8-F2D3C094A6D9@yesql.se*\n<https://www.postgresql.org/message-id/9140106E-F9BF-4D85-8FC8-F2D3C094A6D9@yesql.se>\n\nStill the back-ported version of the Daniel’s patch is attached here too –\njust for convenience.\n\n\n\nWhile the above changes represent the straight work continue, there is\nanother version to consider. Most of the patch problems seem to originate\nfrom the dathasloginevt flag support. There are lots of known problems\n(partly fixed) and probably a lot more unfound. At the same time the flag\nitself is not a critical element, but just a performance optimizer for\nlogging-in of users who are NOT using the on-login triggers.\n\nI have made a simpler version without the flag and tried to compare the\nperformance. The results show that life without dathasloginevt is still\npossible. When there is a small number of non-login event triggers, the\ndifference is barely noticeable indeed. To show the difference, I have\nadded 1000 sql_drop event triggers and used pgbench to continuously query\nthe database for “select 1” with reconnects for 3 seconds. Here are the\nresults. For each version I recorded average connection time with 0 and\nwith 1000 event triggers:\n\nWith dathasloginevt flag: 0.609 ms VS 0.611 ms\n\nNo-flag version: 0.617 ms VS 0.727 ms\n\nYou can see that the difference is noticeable, but not that critical as we\ncan expect for 1000 triggers (while in a vast majority of real cases there\nwould be a much lesser number of triggers). I.e. the flagless version of\nthe patch introduces a huge reliability raise at the cost of a small\nperformance drop.\n\nWhat do you think? Maybe it’s better to use the flagless version? Or even a\nsmall performance drop is considered as unacceptable?\n\n\n\nThe attached files include the two versions of the patch: “v32” for the\nupdated version with flag and “v31_nf” – for the flagless version. Both\nversions contain “0001“ file for the patch itself and “0002” for\nback-ported controlling GUC.\n--\n best regards,\n Mikhail A. Gribkov\n\n\n\nOn Fri, Nov 4, 2022 at 3:58 AM Ian Lawrence Barwick <barwick@gmail.com>\nwrote:\n\n> 2022年11月4日(金) 5:23 Daniel Gustafsson <daniel@yesql.se>:\n> >\n> > > On 20 Sep 2022, at 16:10, Daniel Gustafsson <daniel@yesql.se> wrote:\n> >\n> > > Since the original authors seems to have retired from the patch\n> > > (I've only rebased it to try and help) I am inclined to mark it as\n> returned\n> > > with feedback.\n> >\n> > Doing so now since no updates have been posted for quite some time and\n> holes\n> > have been poked in the patch.\n>\n> I see it was still \"Waiting on Author\" so I went ahead and changed the\n> status.\n>\n> > The GUC for temporarily disabling event triggers, to avoid the need for\n> single-\n> > user mode during troubleshooting, might however be of interest so I will\n> break\n> > that out and post to a new thread.\n>\n> For reference this is the new thread:\n>\n>\n> https://www.postgresql.org/message-id/9140106E-F9BF-4D85-8FC8-F2D3C094A6D9%40yesql.se\n>\n> Regards\n>\n> Ian Barwick\n>\n>\n>", "msg_date": "Tue, 22 Nov 2022 16:53:13 +0300", "msg_from": "Mikhail Gribkov <youzhick@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi hackers,\nAttached v33 is a new rebase of the flagless version of the patch. As\nthere were no objections at first glance, I’ll try to post it to the\nupcoming commitfest, thus the brief recap of all the patch details is below.\n\nv33-On_client_login_event_trigger\nThe patch introduces a trigger on login event, allowing to fire some\nactions right on the user connection. This can be useful for logging or\nconnection check purposes as well as for some personalization of the\nenvironment. Usage details are described in the documentation included, but\nshortly usage is the same as for other triggers: create function returning\nevent_trigger and then create event trigger on login event.\n\nThe patch is prepared to be applied to the master branch and tested when\napplied after e52f8b301ed54aac5162b185b43f5f1e44b6b17e commit by Thomas\nMunro (Date: Fri Dec 16 17:36:22 2022 +1300).\nRegression tests and documentation included.\n\nA couple of words about what and why I changed compared to the previous\nauthor's version.\nFirst, the (en/dis)abling GUC was removed from the patch because\nideologically it is a separate feature and nowadays it’s discussed and\n supported in a separate thread by Daniel Gustaffson:\nhttps://www.postgresql.org/message-id/flat/9140106E-F9BF-4D85-8FC8-F2D3C094A6D9%40yesql.se\nSecond, I have removed the dathasloginevt flag. The flag was initially\nadded to the patch for performance reasons and it did the job, although it\nwas quite a clumsy construct causing tons of bugs and could potentially\nlead to tons more during further PostgreSQL evolution. I have removed the\nflag and found that the performance drop is not that significant.\n\nAnd this is an aspect I should describe in more detail.\nThe possible performance drop is expected as an increased time used to\nlogin a user NOT using a login trigger.\nFirst of all, the method of performance check:\n echo 'select 1;' > ./tst.sql\n pgbench -n -C -T3 -f tst.sql -U postgres postgres\nThe output value \"average connection time\" is the one I use to compare\nperformance.\nNow, what are the results.\n* master branch: 0.641 ms\n* patched version: 0.644 ms\nNo significant difference here and it is just what was expected. Based on\nthe patch design the performance drop can be expected when there are lots\nof event triggers created, but not the login one. Thus I have created 1000\ndrop triggers (the script for creating triggers is attached too) in the\ndatabase and repeated the test:\n* master branch: 0.646 ms\n* patched version: 0.754 ms\nFor 2000 triggers the patched version connection time is further increased\nto 0.862. Thus we have a login time rise in about 16.5% per 1000 event\ntriggers in the database. It is a statistically noticeable value, still I\ndon’t think it’s a critical one we should be afraid of.\nN.B. The exact values of the login times slightly differ from the ones I\nposted in the previous email. Well, that’s the repeatability level we have.\nThis convinces me even more that the observed level of performance drop is\nacceptable.\n--\n best regards,\n Mikhail A. Gribkov\n\ne-mail: youzhick@gmail.com\n*http://www.flickr.com/photos/youzhick/albums\n<http://www.flickr.com/photos/youzhick/albums>*\nhttp://www.strava.com/athletes/5085772\nphone: +7(916)604-71-12\nTelegram: @youzhick", "msg_date": "Fri, 16 Dec 2022 21:14:09 +0300", "msg_from": "Mikhail Gribkov <youzhick@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi,\n\nMikhail, I've checked the patch and previous discussion,\nthe condition mentioned earlier is still actual:\n>The example trigger from the documentation\n\n+DECLARE\n\n+ hour integer = EXTRACT('hour' FROM current_time);\n\n+ rec boolean;\n\n+BEGIN\n\n+-- 1. Forbid logging in between 2AM and 4AM.\n\n+IF hour BETWEEN 2 AND 4 THEN\n\n+ RAISE EXCEPTION 'Login forbidden';\n\n+END IF;\n\n\n>can be bypassed with PGOPTIONS='-c timezone=...'. Probably this is\n>nothing new and concerns any SECURITY DEFINER function, but still...\n\nalong with\n+IF hour BETWEEN 8 AND 20 THEN\nIt seems to be a minor security issue, so just in case you haven't noticed\nit.\n\nOn Fri, Dec 16, 2022 at 9:14 PM Mikhail Gribkov <youzhick@gmail.com> wrote:\n\n> Hi hackers,\n> Attached v33 is a new rebase of the flagless version of the patch. As\n> there were no objections at first glance, I’ll try to post it to the\n> upcoming commitfest, thus the brief recap of all the patch details is below.\n>\n> v33-On_client_login_event_trigger\n> The patch introduces a trigger on login event, allowing to fire some\n> actions right on the user connection. This can be useful for logging or\n> connection check purposes as well as for some personalization of the\n> environment. Usage details are described in the documentation included, but\n> shortly usage is the same as for other triggers: create function returning\n> event_trigger and then create event trigger on login event.\n>\n> The patch is prepared to be applied to the master branch and tested when\n> applied after e52f8b301ed54aac5162b185b43f5f1e44b6b17e commit by Thomas\n> Munro (Date: Fri Dec 16 17:36:22 2022 +1300).\n> Regression tests and documentation included.\n>\n> A couple of words about what and why I changed compared to the previous\n> author's version.\n> First, the (en/dis)abling GUC was removed from the patch because\n> ideologically it is a separate feature and nowadays it’s discussed and\n> supported in a separate thread by Daniel Gustaffson:\n>\n> https://www.postgresql.org/message-id/flat/9140106E-F9BF-4D85-8FC8-F2D3C094A6D9%40yesql.se\n> Second, I have removed the dathasloginevt flag. The flag was initially\n> added to the patch for performance reasons and it did the job, although it\n> was quite a clumsy construct causing tons of bugs and could potentially\n> lead to tons more during further PostgreSQL evolution. I have removed the\n> flag and found that the performance drop is not that significant.\n>\n> And this is an aspect I should describe in more detail.\n> The possible performance drop is expected as an increased time used to\n> login a user NOT using a login trigger.\n> First of all, the method of performance check:\n> echo 'select 1;' > ./tst.sql\n> pgbench -n -C -T3 -f tst.sql -U postgres postgres\n> The output value \"average connection time\" is the one I use to compare\n> performance.\n> Now, what are the results.\n> * master branch: 0.641 ms\n> * patched version: 0.644 ms\n> No significant difference here and it is just what was expected. Based on\n> the patch design the performance drop can be expected when there are lots\n> of event triggers created, but not the login one. Thus I have created 1000\n> drop triggers (the script for creating triggers is attached too) in the\n> database and repeated the test:\n> * master branch: 0.646 ms\n> * patched version: 0.754 ms\n> For 2000 triggers the patched version connection time is further increased\n> to 0.862. Thus we have a login time rise in about 16.5% per 1000 event\n> triggers in the database. It is a statistically noticeable value, still I\n> don’t think it’s a critical one we should be afraid of.\n> N.B. The exact values of the login times slightly differ from the ones I\n> posted in the previous email. Well, that’s the repeatability level we have.\n> This convinces me even more that the observed level of performance drop is\n> acceptable.\n> --\n> best regards,\n> Mikhail A. Gribkov\n>\n> e-mail: youzhick@gmail.com\n> *http://www.flickr.com/photos/youzhick/albums\n> <http://www.flickr.com/photos/youzhick/albums>*\n> http://www.strava.com/athletes/5085772\n> phone: +7(916)604-71-12\n> Telegram: @youzhick\n>\n\n\n-- \nRegards,\nNikita Malakhov\nPostgres Professional\nhttps://postgrespro.ru/\n\nHi,Mikhail, I've checked the patch and previous discussion,the condition mentioned earlier is still actual:>The example trigger from the documentation+DECLARE+  hour integer = EXTRACT('hour' FROM current_time);+  rec boolean;+BEGIN+-- 1. Forbid logging in between 2AM and 4AM.+IF hour BETWEEN 2 AND 4 THEN+  RAISE EXCEPTION 'Login forbidden';+END IF;>can be bypassed with PGOPTIONS='-c timezone=...'. Probably this is>nothing new and concerns any SECURITY DEFINER function, but still...along with+IF hour BETWEEN 8 AND 20 THENIt seems to be a minor security issue, so just in case you haven't noticed it.On Fri, Dec 16, 2022 at 9:14 PM Mikhail Gribkov <youzhick@gmail.com> wrote:Hi hackers,Attached v33 is a new rebase of the flagless version of the patch.  As there were no objections at first glance, I’ll try to post it to the upcoming commitfest, thus the brief recap of all the patch details is below.v33-On_client_login_event_triggerThe patch introduces a trigger on login event, allowing to fire some actions right on the user connection. This can be useful for  logging or connection check purposes as well as for some personalization of the environment. Usage details are described in the documentation included, but shortly usage is the same as for other triggers: create function returning event_trigger and then create event trigger on login event.The patch is prepared to be applied to the master branch and tested when applied after e52f8b301ed54aac5162b185b43f5f1e44b6b17e commit by Thomas Munro (Date:   Fri Dec 16 17:36:22 2022 +1300).Regression tests and documentation included.A couple of words about what and why I changed compared to the previous author's version.First, the (en/dis)abling GUC was removed from the patch because ideologically it is a separate feature and nowadays it’s  discussed and  supported in a separate thread by Daniel Gustaffson:https://www.postgresql.org/message-id/flat/9140106E-F9BF-4D85-8FC8-F2D3C094A6D9%40yesql.seSecond, I have removed the dathasloginevt flag. The flag was initially added to the patch for performance reasons and it did the job, although it was quite a clumsy construct causing tons of bugs and could potentially lead to tons more during further PostgreSQL evolution. I have removed the flag and found that the performance drop is not that significant.And this is an aspect I should describe in more detail.The possible performance drop is expected as an increased time used to login a user NOT using a login trigger.First of all, the method of performance check:    echo 'select 1;' > ./tst.sql    pgbench -n -C -T3 -f tst.sql -U postgres postgresThe output value \"average connection time\" is the one I use to compare performance.Now, what are the results. * master branch: 0.641 ms* patched version: 0.644 msNo significant difference here and it is just what was expected. Based on the patch design the performance drop can be expected when there are lots of event triggers created, but not the login one. Thus I have created 1000 drop triggers (the script for creating triggers is attached too) in the database and repeated the test:* master branch: 0.646 ms* patched version: 0.754 msFor 2000 triggers the patched version connection time is further increased to 0.862. Thus we have a login time rise in about 16.5% per 1000 event triggers in the database. It is a statistically noticeable value, still I don’t think it’s a critical one we should be afraid of.N.B. The exact values of the login times  slightly differ from the ones I posted in the previous email. Well, that’s the repeatability level we have. This convinces me even more that the observed level of performance drop is acceptable.-- best regards,    Mikhail A. Gribkove-mail: youzhick@gmail.comhttp://www.flickr.com/photos/youzhick/albumshttp://www.strava.com/athletes/5085772phone: +7(916)604-71-12Telegram: @youzhick\n-- Regards,Nikita MalakhovPostgres Professional https://postgrespro.ru/", "msg_date": "Fri, 16 Dec 2022 23:17:45 +0300", "msg_from": "Nikita Malakhov <hukutoc@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi Nikita,\n\n> Mikhail, I've checked the patch and previous discussion,\n> the condition mentioned earlier is still actual:\n\nThanks for pointing this out! My bad, I forgot to fix the documentation\nexample.\nAttached v34 has this issue fixed, as well as a couple other problems with\nthe example code.\n\n--\n best regards,\n Mikhail A. Gribkov", "msg_date": "Sat, 17 Dec 2022 14:45:47 +0300", "msg_from": "Mikhail Gribkov <youzhick@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Sat, Dec 17, 2022 at 3:46 AM Mikhail Gribkov <youzhick@gmail.com> wrote:\n\n> Hi Nikita,\n>\n> > Mikhail, I've checked the patch and previous discussion,\n> > the condition mentioned earlier is still actual:\n>\n> Thanks for pointing this out! My bad, I forgot to fix the documentation\n> example.\n> Attached v34 has this issue fixed, as well as a couple other problems with\n> the example code.\n>\n> --\n> best regards,\n> Mikhail A. Gribkov\n>\nHi,\n\nbq. in to the system\n\n'in to' -> into\n\nbq. Any bugs in a trigger procedure\n\nAny bugs -> Any bug\n\n+ if (event == EVT_Login)\n+ dbgtag = CMDTAG_LOGIN;\n+ else\n+ dbgtag = CreateCommandTag(parsetree);\n\nThe same snippet appears more than once. It seems CMDTAG_LOGIN handling can\nbe moved into `CreateCommandTag`.\n\nCheers\n\nOn Sat, Dec 17, 2022 at 3:46 AM Mikhail Gribkov <youzhick@gmail.com> wrote:Hi Nikita,> Mikhail, I've checked the patch and previous discussion,> the condition mentioned earlier is still actual:Thanks for pointing this out! My bad, I forgot to fix the documentation example.Attached v34 has this issue fixed, as well as a couple other problems with the example code.-- best regards,    Mikhail A. GribkovHi,bq. in to the system'in to' -> intobq. Any bugs in a trigger procedureAny bugs -> Any bug+               if (event == EVT_Login)+                       dbgtag = CMDTAG_LOGIN;+               else+                       dbgtag = CreateCommandTag(parsetree);The same snippet appears more than once. It seems CMDTAG_LOGIN handling can be moved into `CreateCommandTag`.Cheers", "msg_date": "Sat, 17 Dec 2022 04:29:17 -0800", "msg_from": "Ted Yu <yuzhihong@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi Ted,\n\n> bq. in to the system\n> 'in to' -> into\n> bq. Any bugs in a trigger procedure\n> Any bugs -> Any bug\n\nThanks! Fixed typos in the attached v35.\n\n> + if (event == EVT_Login)\n> + dbgtag = CMDTAG_LOGIN;\n> + else\n> + dbgtag = CreateCommandTag(parsetree);\n> The same snippet appears more than once. It seems CMDTAG_LOGIN handling\ncan be moved into `CreateCommandTag`.\n\nIt appears twice in fact, both cases are nearby: in the main code and under\nthe assert-checking ifdef.\nMoving CMDTAG_LOGIN to CreateCommandTag would change the CreateCommandTag\nfunction signature and ideology. CreateCommandTag finds a tag based on the\ncommand parse tree, while login event is a specific case when we do not\nhave any command and the parse tree is NULL. Changing CreateCommandTag\nsignature for these two calls looks a little bit overkill as it would lead\nto changing lots of other places the function is called from.\nWe could move this snippet to a separate function, but here are the similar\nconcerns I think: it would make sense for a more common or a more complex\nsnippet, but not for two cases of if-else one-liners.\n\n--\n best regards,\n Mikhail A. Gribkov\n\ne-mail: youzhick@gmail.com\n*http://www.flickr.com/photos/youzhick/albums\n<http://www.flickr.com/photos/youzhick/albums>*\nhttp://www.strava.com/athletes/5085772\nphone: +7(916)604-71-12\nTelegram: @youzhick\n\n\n\nOn Sat, Dec 17, 2022 at 3:29 PM Ted Yu <yuzhihong@gmail.com> wrote:\n\n>\n>\n> On Sat, Dec 17, 2022 at 3:46 AM Mikhail Gribkov <youzhick@gmail.com>\n> wrote:\n>\n>> Hi Nikita,\n>>\n>> > Mikhail, I've checked the patch and previous discussion,\n>> > the condition mentioned earlier is still actual:\n>>\n>> Thanks for pointing this out! My bad, I forgot to fix the documentation\n>> example.\n>> Attached v34 has this issue fixed, as well as a couple other problems\n>> with the example code.\n>>\n>> --\n>> best regards,\n>> Mikhail A. Gribkov\n>>\n> Hi,\n>\n> bq. in to the system\n>\n> 'in to' -> into\n>\n> bq. Any bugs in a trigger procedure\n>\n> Any bugs -> Any bug\n>\n> + if (event == EVT_Login)\n> + dbgtag = CMDTAG_LOGIN;\n> + else\n> + dbgtag = CreateCommandTag(parsetree);\n>\n> The same snippet appears more than once. It seems CMDTAG_LOGIN handling\n> can be moved into `CreateCommandTag`.\n>\n> Cheers\n>", "msg_date": "Mon, 19 Dec 2022 12:40:39 +0300", "msg_from": "Mikhail Gribkov <youzhick@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Mon, Dec 19, 2022 at 1:40 AM Mikhail Gribkov <youzhick@gmail.com> wrote:\n\n> Hi Ted,\n>\n> > bq. in to the system\n> > 'in to' -> into\n> > bq. Any bugs in a trigger procedure\n> > Any bugs -> Any bug\n>\n> Thanks! Fixed typos in the attached v35.\n>\n> > + if (event == EVT_Login)\n> > + dbgtag = CMDTAG_LOGIN;\n> > + else\n> > + dbgtag = CreateCommandTag(parsetree);\n> > The same snippet appears more than once. It seems CMDTAG_LOGIN handling\n> can be moved into `CreateCommandTag`.\n>\n> It appears twice in fact, both cases are nearby: in the main code and\n> under the assert-checking ifdef.\n> Moving CMDTAG_LOGIN to CreateCommandTag would change the CreateCommandTag\n> function signature and ideology. CreateCommandTag finds a tag based on the\n> command parse tree, while login event is a specific case when we do not\n> have any command and the parse tree is NULL. Changing CreateCommandTag\n> signature for these two calls looks a little bit overkill as it would lead\n> to changing lots of other places the function is called from.\n> We could move this snippet to a separate function, but here are the\n> similar concerns I think: it would make sense for a more common or a more\n> complex snippet, but not for two cases of if-else one-liners.\n>\n> --\n> best regards,\n> Mikhail A. Gribkov\n>\n> e-mail: youzhick@gmail.com\n> *http://www.flickr.com/photos/youzhick/albums\n> <http://www.flickr.com/photos/youzhick/albums>*\n> http://www.strava.com/athletes/5085772\n> phone: +7(916)604-71-12\n> Telegram: @youzhick\n>\n> Hi, Mikhail:\nThanks for the explanation.\nIt is Okay to keep the current formation of CMDTAG_LOGIN handling.\n\nCheers\n\nOn Mon, Dec 19, 2022 at 1:40 AM Mikhail Gribkov <youzhick@gmail.com> wrote:Hi Ted,> bq. in to the system> 'in to' -> into> bq. Any bugs in a trigger procedure> Any bugs -> Any bugThanks!  Fixed typos in the attached v35.>   +               if (event == EVT_Login)>   +                       dbgtag = CMDTAG_LOGIN;>   +               else>   +                       dbgtag = CreateCommandTag(parsetree);> The same snippet appears more than once. It seems CMDTAG_LOGIN handling can be moved into `CreateCommandTag`.It appears twice in fact, both cases are nearby: in the main code and under the assert-checking ifdef.Moving CMDTAG_LOGIN to CreateCommandTag would change the CreateCommandTag function signature and ideology. CreateCommandTag finds a tag based on the command parse tree, while login event is a specific case when we do not have any command and the parse tree is NULL. Changing CreateCommandTag signature for these two calls looks a little bit overkill as it would lead to changing lots of other places the function is called from. We could move this snippet to a separate function, but here are the similar concerns I think: it would make sense for a more common or a more complex snippet, but not for two cases of if-else one-liners.-- best regards,    Mikhail A. Gribkove-mail: youzhick@gmail.comhttp://www.flickr.com/photos/youzhick/albumshttp://www.strava.com/athletes/5085772phone: +7(916)604-71-12Telegram: @youzhickHi, Mikhail:Thanks for the explanation.It is Okay to keep the current formation of CMDTAG_LOGIN handling.Cheers", "msg_date": "Mon, 19 Dec 2022 04:44:15 -0800", "msg_from": "Ted Yu <yuzhihong@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi\n\n\npo 19. 12. 2022 v 10:40 odesílatel Mikhail Gribkov <youzhick@gmail.com>\nnapsal:\n\n> Hi Ted,\n>\n> > bq. in to the system\n> > 'in to' -> into\n> > bq. Any bugs in a trigger procedure\n> > Any bugs -> Any bug\n>\n> Thanks! Fixed typos in the attached v35.\n>\n> > + if (event == EVT_Login)\n> > + dbgtag = CMDTAG_LOGIN;\n> > + else\n> > + dbgtag = CreateCommandTag(parsetree);\n> > The same snippet appears more than once. It seems CMDTAG_LOGIN handling\n> can be moved into `CreateCommandTag`.\n>\n> It appears twice in fact, both cases are nearby: in the main code and\n> under the assert-checking ifdef.\n> Moving CMDTAG_LOGIN to CreateCommandTag would change the CreateCommandTag\n> function signature and ideology. CreateCommandTag finds a tag based on the\n> command parse tree, while login event is a specific case when we do not\n> have any command and the parse tree is NULL. Changing CreateCommandTag\n> signature for these two calls looks a little bit overkill as it would lead\n> to changing lots of other places the function is called from.\n> We could move this snippet to a separate function, but here are the\n> similar concerns I think: it would make sense for a more common or a more\n> complex snippet, but not for two cases of if-else one-liners.\n>\n\nI checked this patch and it looks well. All tests passed. Together with\nhttps://commitfest.postgresql.org/41/4013/ it can be a good feature.\n\nI re-tested impact on performance and for the worst case looks like less\nthan 1% (0.8%). I think it is acceptable. Tested pgbench scenario \"SELECT\n1\"\n\npgbench -f ~/test.sql -C -c 3 -j 5 -T 100 -P10 postgres\n\n733 tps (master), 727 tps (patched).\n\nI think raising an exception inside should be better tested - not it is\nonly in 001_stream_rep.pl - generally more tests are welcome - there are no\ntested handling exceptions.\n\nRegards\n\nPavel\n\n\n> --\n> best regards,\n> Mikhail A. Gribkov\n>\n> e-mail: youzhick@gmail.com\n> *http://www.flickr.com/photos/youzhick/albums\n> <http://www.flickr.com/photos/youzhick/albums>*\n> http://www.strava.com/athletes/5085772\n> phone: +7(916)604-71-12\n> Telegram: @youzhick\n>\n>\n>\n> On Sat, Dec 17, 2022 at 3:29 PM Ted Yu <yuzhihong@gmail.com> wrote:\n>\n>>\n>>\n>> On Sat, Dec 17, 2022 at 3:46 AM Mikhail Gribkov <youzhick@gmail.com>\n>> wrote:\n>>\n>>> Hi Nikita,\n>>>\n>>> > Mikhail, I've checked the patch and previous discussion,\n>>> > the condition mentioned earlier is still actual:\n>>>\n>>> Thanks for pointing this out! My bad, I forgot to fix the documentation\n>>> example.\n>>> Attached v34 has this issue fixed, as well as a couple other problems\n>>> with the example code.\n>>>\n>>> --\n>>> best regards,\n>>> Mikhail A. Gribkov\n>>>\n>> Hi,\n>>\n>> bq. in to the system\n>>\n>> 'in to' -> into\n>>\n>> bq. Any bugs in a trigger procedure\n>>\n>> Any bugs -> Any bug\n>>\n>> + if (event == EVT_Login)\n>> + dbgtag = CMDTAG_LOGIN;\n>> + else\n>> + dbgtag = CreateCommandTag(parsetree);\n>>\n>> The same snippet appears more than once. It seems CMDTAG_LOGIN handling\n>> can be moved into `CreateCommandTag`.\n>>\n>> Cheers\n>>\n>\n\nHipo 19. 12. 2022 v 10:40 odesílatel Mikhail Gribkov <youzhick@gmail.com> napsal:Hi Ted,> bq. in to the system> 'in to' -> into> bq. Any bugs in a trigger procedure> Any bugs -> Any bugThanks!  Fixed typos in the attached v35.>   +               if (event == EVT_Login)>   +                       dbgtag = CMDTAG_LOGIN;>   +               else>   +                       dbgtag = CreateCommandTag(parsetree);> The same snippet appears more than once. It seems CMDTAG_LOGIN handling can be moved into `CreateCommandTag`.It appears twice in fact, both cases are nearby: in the main code and under the assert-checking ifdef.Moving CMDTAG_LOGIN to CreateCommandTag would change the CreateCommandTag function signature and ideology. CreateCommandTag finds a tag based on the command parse tree, while login event is a specific case when we do not have any command and the parse tree is NULL. Changing CreateCommandTag signature for these two calls looks a little bit overkill as it would lead to changing lots of other places the function is called from. We could move this snippet to a separate function, but here are the similar concerns I think: it would make sense for a more common or a more complex snippet, but not for two cases of if-else one-liners.I checked this patch and it looks well. All tests passed. Together with https://commitfest.postgresql.org/41/4013/ it can be a good feature.I re-tested impact on performance and for the worst case looks like less than 1% (0.8%). I think it is acceptable. Tested pgbench scenario \"SELECT 1\" pgbench -f ~/test.sql -C -c 3 -j 5 -T 100 -P10 postgres733 tps (master), 727 tps (patched).I think raising an exception inside should be better tested - not it is only in 001_stream_rep.pl - generally more tests are welcome - there are no tested handling exceptions.RegardsPavel-- best regards,    Mikhail A. Gribkove-mail: youzhick@gmail.comhttp://www.flickr.com/photos/youzhick/albumshttp://www.strava.com/athletes/5085772phone: +7(916)604-71-12Telegram: @youzhickOn Sat, Dec 17, 2022 at 3:29 PM Ted Yu <yuzhihong@gmail.com> wrote:On Sat, Dec 17, 2022 at 3:46 AM Mikhail Gribkov <youzhick@gmail.com> wrote:Hi Nikita,> Mikhail, I've checked the patch and previous discussion,> the condition mentioned earlier is still actual:Thanks for pointing this out! My bad, I forgot to fix the documentation example.Attached v34 has this issue fixed, as well as a couple other problems with the example code.-- best regards,    Mikhail A. GribkovHi,bq. in to the system'in to' -> intobq. Any bugs in a trigger procedureAny bugs -> Any bug+               if (event == EVT_Login)+                       dbgtag = CMDTAG_LOGIN;+               else+                       dbgtag = CreateCommandTag(parsetree);The same snippet appears more than once. It seems CMDTAG_LOGIN handling can be moved into `CreateCommandTag`.Cheers", "msg_date": "Thu, 12 Jan 2023 07:50:23 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi Pavel,\n\nThanks for pointing out the tests. I completely agree that using an\nexception inside on-login trigger should be tested. It cannot be done via\nregular *.sql/*.out regress tests, thus I have added another perl test to\nauthentication group doing this.\nAttached v36 patch contains this test along with the fresh rebase on master.\n\n--\n best regards,\n Mikhail A. Gribkov\n\ne-mail: youzhick@gmail.com\n*http://www.flickr.com/photos/youzhick/albums\n<http://www.flickr.com/photos/youzhick/albums>*\nhttp://www.strava.com/athletes/5085772\nphone: +7(916)604-71-12\nTelegram: @youzhick\n\n\n\nOn Thu, Jan 12, 2023 at 9:51 AM Pavel Stehule <pavel.stehule@gmail.com>\nwrote:\n\n> Hi\n>\n> I checked this patch and it looks well. All tests passed. Together with\n> https://commitfest.postgresql.org/41/4013/ it can be a good feature.\n>\n> I re-tested impact on performance and for the worst case looks like less\n> than 1% (0.8%). I think it is acceptable. Tested pgbench scenario \"SELECT\n> 1\"\n>\n> pgbench -f ~/test.sql -C -c 3 -j 5 -T 100 -P10 postgres\n>\n> 733 tps (master), 727 tps (patched).\n>\n> I think raising an exception inside should be better tested - not it is\n> only in 001_stream_rep.pl - generally more tests are welcome - there are\n> no tested handling exceptions.\n>\n> Regards\n>\n> Pavel\n>\n>", "msg_date": "Sun, 15 Jan 2023 00:56:06 +0300", "msg_from": "Mikhail Gribkov <youzhick@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi\n\n\nso 14. 1. 2023 v 22:56 odesílatel Mikhail Gribkov <youzhick@gmail.com>\nnapsal:\n\n> Hi Pavel,\n>\n> Thanks for pointing out the tests. I completely agree that using an\n> exception inside on-login trigger should be tested. It cannot be done via\n> regular *.sql/*.out regress tests, thus I have added another perl test to\n> authentication group doing this.\n> Attached v36 patch contains this test along with the fresh rebase on\n> master.\n>\n> --\n> best regards,\n> Mikhail A. Gribkov\n>\n> e-mail: youzhick@gmail.com\n> *http://www.flickr.com/photos/youzhick/albums\n> <http://www.flickr.com/photos/youzhick/albums>*\n> http://www.strava.com/athletes/5085772\n> phone: +7(916)604-71-12\n> Telegram: @youzhick\n>\n>\n>\n> On Thu, Jan 12, 2023 at 9:51 AM Pavel Stehule <pavel.stehule@gmail.com>\n> wrote:\n>\n>> Hi\n>>\n>> I checked this patch and it looks well. All tests passed. Together with\n>> https://commitfest.postgresql.org/41/4013/ it can be a good feature.\n>>\n>> I re-tested impact on performance and for the worst case looks like less\n>> than 1% (0.8%). I think it is acceptable. Tested pgbench scenario \"SELECT\n>> 1\"\n>>\n>> pgbench -f ~/test.sql -C -c 3 -j 5 -T 100 -P10 postgres\n>>\n>> 733 tps (master), 727 tps (patched).\n>>\n>> I think raising an exception inside should be better tested - not it is\n>> only in 001_stream_rep.pl - generally more tests are welcome - there are\n>> no tested handling exceptions.\n>>\n>\nThank you\n\ncheck-world passed without problems\nbuild doc passed without problems\nI think so tests are now enough\n\nI'll mark this patch as ready for committer\n\nRegards\n\nPavel\n\n\n\n\n>\n>> Regards\n>>\n>> Pavel\n>>\n>>\n\nHiso 14. 1. 2023 v 22:56 odesílatel Mikhail Gribkov <youzhick@gmail.com> napsal:Hi Pavel,Thanks for pointing out the tests. I completely agree that using an exception inside on-login trigger should be tested. It cannot be done via regular *.sql/*.out regress tests, thus I have added another perl test to authentication group doing this.Attached v36 patch contains this test along with the fresh rebase on master.-- best regards,    Mikhail A. Gribkove-mail: youzhick@gmail.comhttp://www.flickr.com/photos/youzhick/albumshttp://www.strava.com/athletes/5085772phone: +7(916)604-71-12Telegram: @youzhickOn Thu, Jan 12, 2023 at 9:51 AM Pavel Stehule <pavel.stehule@gmail.com> wrote:HiI checked this patch and it looks well. All tests passed. Together with https://commitfest.postgresql.org/41/4013/ it can be a good feature.I re-tested impact on performance and for the worst case looks like less than 1% (0.8%). I think it is acceptable. Tested pgbench scenario \"SELECT 1\" pgbench -f ~/test.sql -C -c 3 -j 5 -T 100 -P10 postgres733 tps (master), 727 tps (patched).I think raising an exception inside should be better tested - not it is only in 001_stream_rep.pl - generally more tests are welcome - there are no tested handling exceptions.Thank youcheck-world passed without problemsbuild doc passed without problemsI think so tests are now enoughI'll mark this patch as ready for committerRegardsPavel RegardsPavel", "msg_date": "Sun, 15 Jan 2023 07:32:17 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "ne 15. 1. 2023 v 7:32 odesílatel Pavel Stehule <pavel.stehule@gmail.com>\nnapsal:\n\n> Hi\n>\n>\n>> On Thu, Jan 12, 2023 at 9:51 AM Pavel Stehule <pavel.stehule@gmail.com>\n>> wrote:\n>>\n>>> Hi\n>>>\n>>> I checked this patch and it looks well. All tests passed. Together with\n>>> https://commitfest.postgresql.org/41/4013/ it can be a good feature.\n>>>\n>>> I re-tested impact on performance and for the worst case looks like less\n>>> than 1% (0.8%). I think it is acceptable. Tested pgbench scenario \"SELECT\n>>> 1\"\n>>>\n>>> pgbench -f ~/test.sql -C -c 3 -j 5 -T 100 -P10 postgres\n>>>\n>>> 733 tps (master), 727 tps (patched).\n>>>\n>>> I think raising an exception inside should be better tested - not it is\n>>> only in 001_stream_rep.pl - generally more tests are welcome - there\n>>> are no tested handling exceptions.\n>>>\n>>\n> Thank you\n>\n> check-world passed without problems\n> build doc passed without problems\n> I think so tests are now enough\n>\n> I'll mark this patch as ready for committer\n>\n\nUnfortunately, I forgot one important point. There are not any tests\nrelated to backup.\n\nI miss pg_dump related tests.\n\nI mark this patch as waiting on the author.\n\nRegards\n\nPavel\n\n\n\n> Regards\n>\n> Pavel\n>\n>\n>\n>\n>>\n>>> Regards\n>>>\n>>> Pavel\n>>>\n>>>\n\nne 15. 1. 2023 v 7:32 odesílatel Pavel Stehule <pavel.stehule@gmail.com> napsal:HiOn Thu, Jan 12, 2023 at 9:51 AM Pavel Stehule <pavel.stehule@gmail.com> wrote:HiI checked this patch and it looks well. All tests passed. Together with https://commitfest.postgresql.org/41/4013/ it can be a good feature.I re-tested impact on performance and for the worst case looks like less than 1% (0.8%). I think it is acceptable. Tested pgbench scenario \"SELECT 1\" pgbench -f ~/test.sql -C -c 3 -j 5 -T 100 -P10 postgres733 tps (master), 727 tps (patched).I think raising an exception inside should be better tested - not it is only in 001_stream_rep.pl - generally more tests are welcome - there are no tested handling exceptions.Thank youcheck-world passed without problemsbuild doc passed without problemsI think so tests are now enoughI'll mark this patch as ready for committerUnfortunately, I  forgot one important point. There are not any tests related to backup.I miss pg_dump related tests.I mark this patch as waiting on the author.RegardsPavelRegardsPavel RegardsPavel", "msg_date": "Mon, 16 Jan 2023 07:09:51 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi Pavel,\n\nOn Mon, Jan 16, 2023 at 9:10 AM Pavel Stehule <pavel.stehule@gmail.com>\nwrote:\n\n>\n>\n> ne 15. 1. 2023 v 7:32 odesílatel Pavel Stehule <pavel.stehule@gmail.com>\n> napsal:\n>\n>> Hi\n>>\n>>\n>>> On Thu, Jan 12, 2023 at 9:51 AM Pavel Stehule <pavel.stehule@gmail.com>\n>>> wrote:\n>>>\n>>>> Hi\n>>>>\n>>>> I checked this patch and it looks well. All tests passed. Together with\n>>>> https://commitfest.postgresql.org/41/4013/ it can be a good feature.\n>>>>\n>>>> I re-tested impact on performance and for the worst case looks like\n>>>> less than 1% (0.8%). I think it is acceptable. Tested pgbench scenario\n>>>> \"SELECT 1\"\n>>>>\n>>>> pgbench -f ~/test.sql -C -c 3 -j 5 -T 100 -P10 postgres\n>>>>\n>>>> 733 tps (master), 727 tps (patched).\n>>>>\n>>>> I think raising an exception inside should be better tested - not it is\n>>>> only in 001_stream_rep.pl - generally more tests are welcome - there\n>>>> are no tested handling exceptions.\n>>>>\n>>>\n>> Thank you\n>>\n>> check-world passed without problems\n>> build doc passed without problems\n>> I think so tests are now enough\n>>\n>> I'll mark this patch as ready for committer\n>>\n>\n> Unfortunately, I forgot one important point. There are not any tests\n> related to backup.\n>\n> I miss pg_dump related tests.\n>\n> I mark this patch as waiting on the author.\n>\n>\n\nThanks for noticing this.\nI have added sections to pg_dump tests. Attached v37 patch contains these\nadditions along with the fresh rebase on master.\n\n--\n best regards,\n Mikhail A. Gribkov\n\ne-mail: youzhick@gmail.com\n*http://www.flickr.com/photos/youzhick/albums\n<http://www.flickr.com/photos/youzhick/albums>*\nhttp://www.strava.com/athletes/5085772\nphone: +7(916)604-71-12\nTelegram: @youzhick\n\n\n>>>>\n>>>>", "msg_date": "Fri, 20 Jan 2023 21:46:42 +0300", "msg_from": "Mikhail Gribkov <youzhick@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "pá 20. 1. 2023 v 19:46 odesílatel Mikhail Gribkov <youzhick@gmail.com>\nnapsal:\n\n> Hi Pavel,\n>\n> On Mon, Jan 16, 2023 at 9:10 AM Pavel Stehule <pavel.stehule@gmail.com>\n> wrote:\n>\n>>\n>>\n>> ne 15. 1. 2023 v 7:32 odesílatel Pavel Stehule <pavel.stehule@gmail.com>\n>> napsal:\n>>\n>>> Hi\n>>>\n>>>\n>>>> On Thu, Jan 12, 2023 at 9:51 AM Pavel Stehule <pavel.stehule@gmail.com>\n>>>> wrote:\n>>>>\n>>>>> Hi\n>>>>>\n>>>>> I checked this patch and it looks well. All tests passed. Together\n>>>>> with https://commitfest.postgresql.org/41/4013/ it can be a good\n>>>>> feature.\n>>>>>\n>>>>> I re-tested impact on performance and for the worst case looks like\n>>>>> less than 1% (0.8%). I think it is acceptable. Tested pgbench scenario\n>>>>> \"SELECT 1\"\n>>>>>\n>>>>> pgbench -f ~/test.sql -C -c 3 -j 5 -T 100 -P10 postgres\n>>>>>\n>>>>> 733 tps (master), 727 tps (patched).\n>>>>>\n>>>>> I think raising an exception inside should be better tested - not it\n>>>>> is only in 001_stream_rep.pl - generally more tests are welcome -\n>>>>> there are no tested handling exceptions.\n>>>>>\n>>>>\n>>> Thank you\n>>>\n>>> check-world passed without problems\n>>> build doc passed without problems\n>>> I think so tests are now enough\n>>>\n>>> I'll mark this patch as ready for committer\n>>>\n>>\n>> Unfortunately, I forgot one important point. There are not any tests\n>> related to backup.\n>>\n>> I miss pg_dump related tests.\n>>\n>> I mark this patch as waiting on the author.\n>>\n>>\n>\n> Thanks for noticing this.\n> I have added sections to pg_dump tests. Attached v37 patch contains these\n> additions along with the fresh rebase on master.\n>\n\nThank you\n\nmarked as ready for committer\n\nRegards\n\nPavel\n\n\n>\n> --\n> best regards,\n> Mikhail A. Gribkov\n>\n> e-mail: youzhick@gmail.com\n> *http://www.flickr.com/photos/youzhick/albums\n> <http://www.flickr.com/photos/youzhick/albums>*\n> http://www.strava.com/athletes/5085772\n> phone: +7(916)604-71-12\n> Telegram: @youzhick\n>\n>\n>>>>>\n>>>>>\n\npá 20. 1. 2023 v 19:46 odesílatel Mikhail Gribkov <youzhick@gmail.com> napsal:  Hi Pavel,On Mon, Jan 16, 2023 at 9:10 AM Pavel Stehule <pavel.stehule@gmail.com> wrote:ne 15. 1. 2023 v 7:32 odesílatel Pavel Stehule <pavel.stehule@gmail.com> napsal:HiOn Thu, Jan 12, 2023 at 9:51 AM Pavel Stehule <pavel.stehule@gmail.com> wrote:HiI checked this patch and it looks well. All tests passed. Together with https://commitfest.postgresql.org/41/4013/ it can be a good feature.I re-tested impact on performance and for the worst case looks like less than 1% (0.8%). I think it is acceptable. Tested pgbench scenario \"SELECT 1\"pgbench -f ~/test.sql -C -c 3 -j 5 -T 100 -P10 postgres733 tps (master), 727 tps (patched).I think raising an exception inside should be better tested - not it is only in 001_stream_rep.pl - generally more tests are welcome - there are no tested handling exceptions.Thank youcheck-world passed without problemsbuild doc passed without problemsI think so tests are now enoughI'll mark this patch as ready for committerUnfortunately, I  forgot one important point. There are not any tests related to backup.I miss pg_dump related tests.I mark this patch as waiting on the author. Thanks for noticing this.I have added sections to pg_dump tests. Attached v37 patch contains these additions along with the fresh rebase on master.Thank youmarked as ready for committerRegardsPavel -- best regards,    Mikhail A. Gribkove-mail: youzhick@gmail.comhttp://www.flickr.com/photos/youzhick/albumshttp://www.strava.com/athletes/5085772phone: +7(916)604-71-12Telegram: @youzhick", "msg_date": "Sat, 21 Jan 2023 17:11:07 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi hackers,\n\nThe attached v38 patch is a fresh rebase on master branch.\nNothing has changed beyond rebasing.\n\nAnd just for convenience, here is a link to the exact message of the thread\ndescribing the current approach:\nhttps://www.postgresql.org/message-id/CAMEv5_vg4aJOoUC74XJm%2B5B7%2BTF1nT-Yhtg%2BawtBOESXG5Grfg%40mail.gmail.com\n\n--\n best regards,\n Mikhail A. Gribkov\n\ne-mail: youzhick@gmail.com\n*http://www.flickr.com/photos/youzhick/albums\n<http://www.flickr.com/photos/youzhick/albums>*\nhttp://www.strava.com/athletes/5085772\nphone: +7(916)604-71-12\nTelegram: @youzhick\n\n\n> Thank you\n>\n> marked as ready for committer\n>\n> Regards\n>\n> Pavel\n>\n>\n>>", "msg_date": "Wed, 1 Mar 2023 16:12:14 +0300", "msg_from": "Mikhail Gribkov <youzhick@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "It looks like Daniel Gustafsson, Andres, and Tom have all weighed in\non this patch with at least a neutral comment (+-0 from Andres :)\n\nIt looks like the main concern was breaking physical replicas and that\nthere was consensus that as long as single-user mode worked that it\nwas ok?\n\nSo maybe it's time after 2 1/2 years to get this one committed?\n\n-- \nGregory Stark\nAs Commitfest Manager\n\n\n", "msg_date": "Mon, 6 Mar 2023 15:55:01 -0500", "msg_from": "\"Gregory Stark (as CFM)\" <stark.cfm@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 6 Mar 2023, at 21:55, Gregory Stark (as CFM) <stark.cfm@gmail.com> wrote:\n> \n> It looks like Daniel Gustafsson, Andres, and Tom have all weighed in\n> on this patch with at least a neutral comment (+-0 from Andres :)\n\nI think the concept of a login event trigger has merits, even though it's kind\nof a niche use case.\n\n> It looks like the main concern was breaking physical replicas and that\n> there was consensus that as long as single-user mode worked that it\n> was ok?\n\nHaving a way to not rely on single-user mode and not causing an unacceptable\nperformance hit (which judging by recent benchmarks might not be an issue?). I\nstill intend to revisit this and I hope to get to it during this CF.\n\n--\nDaniel Gustafsson\n\n\n\n", "msg_date": "Mon, 6 Mar 2023 22:24:30 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi,\n\nOn 2023-03-06 15:55:01 -0500, Gregory Stark (as CFM) wrote:\n> It looks like Daniel Gustafsson, Andres, and Tom have all weighed in\n> on this patch with at least a neutral comment (+-0 from Andres :)\n> \n> It looks like the main concern was breaking physical replicas and that\n> there was consensus that as long as single-user mode worked that it\n> was ok?\n\nI don't think it's OK with just single user mode as an scape hatch. We need\nthe GUC that was discussed as part of the thread (and I think there's a patch\nfor that too).\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 6 Mar 2023 14:10:10 -0800", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 6 Mar 2023, at 23:10, Andres Freund <andres@anarazel.de> wrote:\n> \n> Hi,\n> \n> On 2023-03-06 15:55:01 -0500, Gregory Stark (as CFM) wrote:\n>> It looks like Daniel Gustafsson, Andres, and Tom have all weighed in\n>> on this patch with at least a neutral comment (+-0 from Andres :)\n>> \n>> It looks like the main concern was breaking physical replicas and that\n>> there was consensus that as long as single-user mode worked that it\n>> was ok?\n> \n> I don't think it's OK with just single user mode as an scape hatch. We need\n> the GUC that was discussed as part of the thread (and I think there's a patch\n> for that too).\n\nThis is the patch which originated from this thread:\n\n\thttps://commitfest.postgresql.org/42/4013/\n\n--\nDaniel Gustafsson\n\n\n\n", "msg_date": "Mon, 6 Mar 2023 23:18:18 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "It looks like the patch is failing a test by not dumping\nlogin_event_trigger_func? I'm guessing there's a race condition in the\ntest but I don't know. I also don't see the tmp_test_jI6t output file\nbeing preserved in the artifacts anywhere :(\n\nhttps://cirrus-ci.com/task/6391161871400960?logs=test_world#L2671\n\n\n[16:16:48.594] # Looks like you failed 1 test of 10350.\n\n\n# Running: pg_dump --no-sync\n--file=/tmp/cirrus-ci-build/src/bin/pg_dump/tmp_check/tmp_test_jI6t/only_dump_measurement.sql\n--table-and-children=dump_test.measurement --lock-wait-timeout=180000\npostgres\n[16:16:27.027](0.154s) ok 6765 - only_dump_measurement: pg_dump runs\n.....\n[16:16:27.035](0.000s) not ok 6870 - only_dump_measurement: should\ndump CREATE FUNCTION dump_test.login_event_trigger_func\n[16:16:27.035](0.000s)\n[16:16:27.035](0.000s) # Failed test 'only_dump_measurement: should\ndump CREATE FUNCTION dump_test.login_event_trigger_func'\n# at t/002_pg_dump.pl line 4761.\n.....\n[16:16:48.594] +++ tap check in src/bin/pg_dump +++\n[16:16:48.594] [16:16:05] t/001_basic.pl ................ ok 612 ms (\n0.01 usr 0.00 sys + 0.24 cusr 0.26 csys = 0.51 CPU)\n[16:16:48.594]\n[16:16:48.594] # Failed test 'only_dump_measurement: should dump\nCREATE FUNCTION dump_test.login_event_trigger_func'\n[16:16:48.594] # at t/002_pg_dump.pl line 4761.\n[16:16:48.594] # Review only_dump_measurement results in\n/tmp/cirrus-ci-build/src/bin/pg_dump/tmp_check/tmp_test_jI6t\n\n\n", "msg_date": "Wed, 15 Mar 2023 13:44:41 -0400", "msg_from": "\"Gregory Stark (as CFM)\" <stark.cfm@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi Gregory,\n\nThanks for the note. The problem was that the patch was not aware of\nyesterday Tom Lane's changes in the test.\nIt's fixed now: the attached v39 patch contains the updated version along\nwith the freshest rebase on master branch.\n\n--\n best regards,\n Mikhail A. Gribkov\n\ne-mail: youzhick@gmail.com\n*http://www.flickr.com/photos/youzhick/albums\n<http://www.flickr.com/photos/youzhick/albums>*\nhttp://www.strava.com/athletes/5085772\nphone: +7(916)604-71-12\nTelegram: @youzhick\n\n\n\nOn Wed, Mar 15, 2023 at 8:45 PM Gregory Stark (as CFM) <stark.cfm@gmail.com>\nwrote:\n\n> It looks like the patch is failing a test by not dumping\n> login_event_trigger_func? I'm guessing there's a race condition in the\n> test but I don't know. I also don't see the tmp_test_jI6t output file\n> being preserved in the artifacts anywhere :(\n>\n> https://cirrus-ci.com/task/6391161871400960?logs=test_world#L2671\n>\n>\n> [16:16:48.594] # Looks like you failed 1 test of 10350.\n>\n>\n> # Running: pg_dump --no-sync\n>\n> --file=/tmp/cirrus-ci-build/src/bin/pg_dump/tmp_check/tmp_test_jI6t/only_dump_measurement.sql\n> --table-and-children=dump_test.measurement --lock-wait-timeout=180000\n> postgres\n> [16:16:27.027](0.154s) ok 6765 - only_dump_measurement: pg_dump runs\n> .....\n> [16:16:27.035](0.000s) not ok 6870 - only_dump_measurement: should\n> dump CREATE FUNCTION dump_test.login_event_trigger_func\n> [16:16:27.035](0.000s)\n> [16:16:27.035](0.000s) # Failed test 'only_dump_measurement: should\n> dump CREATE FUNCTION dump_test.login_event_trigger_func'\n> # at t/002_pg_dump.pl line 4761.\n> .....\n> [16:16:48.594] +++ tap check in src/bin/pg_dump +++\n> [16:16:48.594] [16:16:05] t/001_basic.pl ................ ok 612 ms (\n> 0.01 usr 0.00 sys + 0.24 cusr 0.26 csys = 0.51 CPU)\n> [16:16:48.594]\n> [16:16:48.594] # Failed test 'only_dump_measurement: should dump\n> CREATE FUNCTION dump_test.login_event_trigger_func'\n> [16:16:48.594] # at t/002_pg_dump.pl line 4761.\n> [16:16:48.594] # Review only_dump_measurement results in\n> /tmp/cirrus-ci-build/src/bin/pg_dump/tmp_check/tmp_test_jI6t\n>", "msg_date": "Wed, 15 Mar 2023 23:23:12 +0300", "msg_from": "Mikhail Gribkov <youzhick@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Tue, Mar 15, 2022 at 4:52 PM Daniel Gustafsson <daniel@yesql.se> wrote:\n> Yeah, that was the previously posted v25 from the author (who adopted it from\n> the original author). I took the liberty to quickly poke at the review\n> comments you had left as well as the ones that I had found to try and progress\n> the patch. 0001 should really go in it's own thread though to not hide it from\n> anyone interested who isn't looking at this thread.\n\nSome comments on 0001:\n\n- In general, I think we should prefer to phrase options in terms of\nwhat is done, rather than what is not done. For instance, the\ncorresponding GUC for row-level security is row_security={on|off}, not\nignore_row_security.\n\n- I think it's odd that the GUC in question doesn't accept true and\nfalse and our usual synonyms for those values. I suggest that it\nshould, even if we want to add more possible values later.\n\n- \"ignoreing\" is mispleled. So is gux-ignore-event-trigger. \"Even\ntriggers\" -> \"Event triggers\".\n\n- Perhaps the documentation for the GUC should mention that the GUC is\nnot relevant in single-user mode because event triggers don't fire\nthen anyway.\n\n- \"Disable event triggers during the session.\" isn't a very good\ndescription because there is in theory nothing to prevent this from\nbeing set in postgresql.conf.\n\nBasically, I think 0001 is a good idea -- I'm much more nervous about\n0002. I think we should get 0001 polished up and committed.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 22 Mar 2023 13:54:37 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 22 Mar 2023, at 18:54, Robert Haas <robertmhaas@gmail.com> wrote:\n\n> Basically, I think 0001 is a good idea -- I'm much more nervous about\n> 0002. I think we should get 0001 polished up and committed.\n\nCorrect me if I'm wrong, but I believe you commented on v27-0001 of the login\nevent trigger patch series? Sorry about the confusion if so, this is a very\nold and lengthy thread with many twists and turns. This series was closed\ndownthread when the original authors of login EVT left, and the 0001 GUC patch\nextracted into its own thread. That patch now lives at:\n\n\thttps://commitfest.postgresql.org/42/4013/\n\nThis thread was then later revived by Mikhail Gribkov but without 0001 instead\nreferring to the above patch for that part.\n\nThe new patch for 0001 is quite different, and I welcome your eyes on that\nsince I agree with you that it would be a good idea.\n\n--\nDaniel Gustafsson\n\n\n\n", "msg_date": "Wed, 22 Mar 2023 20:38:09 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi hackers,\n\nThe attached v40 patch is a fresh rebase on master branch to actualize the\nstate before the upcoming commitfest.\nNothing has changed beyond rebasing.\n\nAnd just for convenience, here is a link to the exact message of the thread\ndescribing the current approach:\nhttps://www.postgresql.org/message-id/CAMEv5_vg4aJOoUC74XJm%2B5B7%2BTF1nT-Yhtg%2BawtBOESXG5Grfg%40mail.gmail.com\n\n--\n best regards,\n Mikhail A. Gribkov\n\ne-mail: youzhick@gmail.com\n*http://www.flickr.com/photos/youzhick/albums\n<http://www.flickr.com/photos/youzhick/albums>*\nhttp://www.strava.com/athletes/5085772\nphone: +7(916)604-71-12\nTelegram: @youzhick\n\n\n\nOn Wed, Mar 22, 2023 at 10:38 PM Daniel Gustafsson <daniel@yesql.se> wrote:\n\n> > On 22 Mar 2023, at 18:54, Robert Haas <robertmhaas@gmail.com> wrote:\n>\n> > Basically, I think 0001 is a good idea -- I'm much more nervous about\n> > 0002. I think we should get 0001 polished up and committed.\n>\n> Correct me if I'm wrong, but I believe you commented on v27-0001 of the\n> login\n> event trigger patch series? Sorry about the confusion if so, this is a\n> very\n> old and lengthy thread with many twists and turns. This series was closed\n> downthread when the original authors of login EVT left, and the 0001 GUC\n> patch\n> extracted into its own thread. That patch now lives at:\n>\n> https://commitfest.postgresql.org/42/4013/\n>\n> This thread was then later revived by Mikhail Gribkov but without 0001\n> instead\n> referring to the above patch for that part.\n>\n> The new patch for 0001 is quite different, and I welcome your eyes on that\n> since I agree with you that it would be a good idea.\n>\n> --\n> Daniel Gustafsson\n>\n>\n>\n>", "msg_date": "Wed, 14 Jun 2023 22:49:15 +0300", "msg_from": "Mikhail Gribkov <youzhick@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi!\n\nOn Wed, Jun 14, 2023 at 10:49 PM Mikhail Gribkov <youzhick@gmail.com> wrote:\n> The attached v40 patch is a fresh rebase on master branch to actualize the state before the upcoming commitfest.\n> Nothing has changed beyond rebasing.\n>\n> And just for convenience, here is a link to the exact message of the thread\n> describing the current approach:\n> https://www.postgresql.org/message-id/CAMEv5_vg4aJOoUC74XJm%2B5B7%2BTF1nT-Yhtg%2BawtBOESXG5Grfg%40mail.gmail.com\n\nThank you for the update. I think the patch is interesting and\ndemanding. The code, docs and tests seem to be quite polished\nalready. Simultaneously, the thread is long and spread over a long\ntime. So, it's easy to lose track. I'd like to do a short summary of\ndesign issues on this thread.\n\n1. Initially the patch introduced \"on login\" triggers. It was unclear\nif they need to rerun on RESET ALL or DISCARD ALL [1]. The new name is\n\"client connection\" trigger, which seems fine [2].\n\n2. Another question is how to deal with triggers, which hangs or fails\nwith error [1]. One possible way to workaround that is single-user\nmode, which is already advised to workaround the errors in other event\ntriggers. However, in perspective single-user mode might be deleted.\nAlso, single-user mode is considered as a worst-case scenario recovery\ntool, while it's very easy to block the database connections with\nclient connection triggers. As addition/alternative to single-user\nmode, GUC options to disable all event triggers and/or client\nconnection triggers. Finally, the patch for the GUC option to disable\nall event triggers resides in a separate thread [4]. Apparently that\npatch should be committed first [5].\n\n3. Yet another question is connection-time overhead introduced by this\npatch. The overhead estimate varies from no measurable overhead [6] to\n5% overhead [7]. In order to overcome that, [8] has introduced a\ndatabase-level flag indicating whether there are connection triggers.\nLater this flag was removed [9] in a hope that the possible overhead\nis acceptable.\n\n4. [10] points that there is no clean way to store information about\nunsuccessful connections (declined by either authentication or\ntrigger). However, this is considered out-of-scope for the current\npatch, and could be implemented later if needed.\n\n5. It was also pointed out [11] that ^C in psql doesn't cancel\nlong-running client connection triggers. That might be considered a\npsql problem though.\n\n6. It has been also pointed out that [12] all triggers, which write\ndata to the database, must check pg_is_in_recovery() to work correctly\non standby. That seems to be currently reflected in the documentation.\n\nSo, for me the open issues seem to be 2, 3 and 5. My plan to revive\nthis patch is to commit the GUC patch [4], recheck the overhead and\nprobably leave \"^C in psql\" problem as a separate standalone issue.\nAny thoughts?\n\nLinks.\n\n1. https://www.postgresql.org/message-id/CAFj8pRBdqdqvkU3mVKzoOnO+jPz-6manRV47CDEa+1jD6x6LFg%40mail.gmail.com\n2. https://www.postgresql.org/message-id/CAFj8pRCxdQgHy8Mynk3hz6pFsqQ9BN6Vfgy0MJLtQBAUhWDf3w%40mail.gmail.com\n3. https://www.postgresql.org/message-id/E0D5DC61-C490-45BD-A984-E8D56493EC4F%40yesql.se\n4. https://www.postgresql.org/message-id/9140106E-F9BF-4D85-8FC8-F2D3C094A6D9@yesql.se\n5. https://www.postgresql.org/message-id/20230306221010.gszjoakt5jp7oqpd%40awork3.anarazel.de\n6. https://www.postgresql.org/message-id/90760f2d-2f9c-12ab-d2c5-e8e6fb7d08de%40postgrespro.ru\n7. https://www.postgresql.org/message-id/CAFj8pRChwu01VLx76nKBVyScHCsd1YnBGiKfDJ6h17g4CSnUBg%40mail.gmail.com\n8. https://www.postgresql.org/message-id/4471d472-5dfc-f2b0-ad05-0ff8d0a3bb0c%40postgrespro.ru\n9. https://www.postgresql.org/message-id/CAMEv5_vg4aJOoUC74XJm%2B5B7%2BTF1nT-Yhtg%2BawtBOESXG5Grfg%40mail.gmail.com\n10. https://www.postgresql.org/message-id/9c897136-4755-dcfc-2d24-b12bcfe4467f%40sigaev.ru\n11. https://www.postgresql.org/message-id/CA%2BTgmoZv9f1s797tihx-zXQN4AE4ZFBV5C0K%3DzngbgNu3xNNkg%40mail.gmail.com\n12. https://www.postgresql.org/message-id/20220312024652.lvgehszwke4hhove%40alap3.anarazel.de\n\n------\nRegards,\nAlexander Korotkov\n\n\n", "msg_date": "Mon, 25 Sep 2023 12:13:04 +0300", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 25 Sep 2023, at 11:13, Alexander Korotkov <aekorotkov@gmail.com> wrote:\n\n> I'd like to do a short summary of\n> design issues on this thread.\n\nThanks for summarizing this long thread!\n\n> the patch for the GUC option to disable\n> all event triggers resides in a separate thread [4]. Apparently that\n> patch should be committed first [5].\n\nI have committed the prerequisite patch for temporarily disabling EVTs via a\nGUC in 7750fefdb2. We should absolutely avoid creating any more dependencies\non single-user mode (yes, I have changed my mind since the beginning of the\nthread).\n\n> 3. Yet another question is connection-time overhead introduced by this\n> patch. The overhead estimate varies from no measurable overhead [6] to\n> 5% overhead [7]. In order to overcome that, [8] has introduced a\n> database-level flag indicating whether there are connection triggers.\n> Later this flag was removed [9] in a hope that the possible overhead\n> is acceptable.\n\nWhile I disliked the flag, I do think the overhead is problematic. Last time I\nprofiled it I found it noticeable, and it seems expensive for such a niche\nfeature to impact such a hot path. Maybe you can think of other ways to reduce\nthe cost here (if it indeed is an issue in the latest version of the patch,\nwhich is not one I've benchmarked)?\n\n> 5. It was also pointed out [11] that ^C in psql doesn't cancel\n> long-running client connection triggers. That might be considered a\n> psql problem though.\n\nWhile it is a psql problem, it's exacerbated by a slow login EVT and it breaks\nwhat I would guess is the mental model of many who press ^C in a stalled login.\nAt the very least we should probably document the risk?\n\n--\nDaniel Gustafsson\n\n\n\n", "msg_date": "Mon, 25 Sep 2023 14:42:15 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi, Daniel!\n\nOn Mon, Sep 25, 2023 at 3:42 PM Daniel Gustafsson <daniel@yesql.se> wrote:\n> > On 25 Sep 2023, at 11:13, Alexander Korotkov <aekorotkov@gmail.com> wrote:\n>\n> > I'd like to do a short summary of\n> > design issues on this thread.\n>\n> Thanks for summarizing this long thread!\n>\n> > the patch for the GUC option to disable\n> > all event triggers resides in a separate thread [4]. Apparently that\n> > patch should be committed first [5].\n>\n> I have committed the prerequisite patch for temporarily disabling EVTs via a\n> GUC in 7750fefdb2. We should absolutely avoid creating any more dependencies\n> on single-user mode (yes, I have changed my mind since the beginning of the\n> thread).\n\nThank you for committing 7750fefdb2. I've revised this patch\naccording to it. I've resolved the conflicts, make use of\nevent_triggers GUC and adjusted some comments.\n\n> > 3. Yet another question is connection-time overhead introduced by this\n> > patch. The overhead estimate varies from no measurable overhead [6] to\n> > 5% overhead [7]. In order to overcome that, [8] has introduced a\n> > database-level flag indicating whether there are connection triggers.\n> > Later this flag was removed [9] in a hope that the possible overhead\n> > is acceptable.\n>\n> While I disliked the flag, I do think the overhead is problematic. Last time I\n> profiled it I found it noticeable, and it seems expensive for such a niche\n> feature to impact such a hot path. Maybe you can think of other ways to reduce\n> the cost here (if it indeed is an issue in the latest version of the patch,\n> which is not one I've benchmarked)?\n\nI don't think I can reproduce the performance regression pointed out\nby Pavel Stehule [1].\n\nI run a simple \";\" sql script (this script doesn't even get the\nsnapshot) on my laptop and run it multiple times with event_triggers =\non and event_triggers = off;\n\npgbench -c 10 -j 10 -M prepared -f 1.sql -P 1 -T 60 -C postgres\nevent_triggers = on\nrun1: 2261\nrun2: 2301\nrun3: 2281\nevent_triggers = off\nrun1: 2321\nrun2: 2277\nrun3: 2267\n\npgbench -c 10 -j 10 -M prepared -f 1.sql -P 1 -T 60 -C postgres\nevent_triggers = on\nrun1: 731\nrun2: 740\nrun3: 733\nevent_triggers = off\nrun1: 739\nrun2: 734\nrun3: 731\n\nI can't confirm the measurable overhead.\n\n> > 5. It was also pointed out [11] that ^C in psql doesn't cancel\n> > long-running client connection triggers. That might be considered a\n> > psql problem though.\n>\n> While it is a psql problem, it's exacerbated by a slow login EVT and it breaks\n> what I would guess is the mental model of many who press ^C in a stalled login.\n> At the very least we should probably document the risk?\n\nDone in the attached patch.\n\nLinks\n1. https://www.postgresql.org/message-id/CAFj8pRChwu01VLx76nKBVyScHCsd1YnBGiKfDJ6h17g4CSnUBg%40mail.gmail.com\n\n------\nRegards,\nAlexander Korotkov", "msg_date": "Fri, 29 Sep 2023 00:50:32 +0300", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 28 Sep 2023, at 23:50, Alexander Korotkov <aekorotkov@gmail.com> wrote:\n\n> I don't think I can reproduce the performance regression pointed out\n> by Pavel Stehule [1].\n\n> I can't confirm the measurable overhead.\n\n\nRunning the same pgbench command on my laptop looking at the average connection\ntimes, and the averaging that over five runs (low/avg/high) I see ~5% increase\nover master with the patched version (compiled without assertions and debug):\n\nPatched event_triggers on: 6.858 ms/7.038 ms/7.434 ms\nPatched event_triggers off: 6.601 ms/6.958 ms/7.539 ms\nMaster: 6.676 ms/6.697 ms/6.760 ms\n\nThis is all quite unscientific with a lot of jitter so grains of salt are to be\napplied, but I find it odd that you don't see any measurable effect. Are you\nseeing the same/similar connection times between master and with this patch\napplied?\n\nA few small comments on the patch:\n\n+ prevent successful login to the system. Such bugs may be fixed by\n+ restarting the system in single-user mode (as event triggers are\nThis paragraph should be reworded to recommend the GUC instead of single-user\nmode (while retaining mention of single-user mode, just not as the primary\noption).\n\n\n+ Also, it's recommended to evade long-running queries in\ns/evade/avoid/ perhaps?\n\n\nThanks for working on this!\n\n--\nDaniel Gustafsson\n\n\n\n", "msg_date": "Fri, 29 Sep 2023 12:15:30 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Fri, Sep 29, 2023 at 1:15 PM Daniel Gustafsson <daniel@yesql.se> wrote:\n> > On 28 Sep 2023, at 23:50, Alexander Korotkov <aekorotkov@gmail.com> wrote:\n>\n> > I don't think I can reproduce the performance regression pointed out\n> > by Pavel Stehule [1].\n>\n> > I can't confirm the measurable overhead.\n>\n>\n> Running the same pgbench command on my laptop looking at the average connection\n> times, and the averaging that over five runs (low/avg/high) I see ~5% increase\n> over master with the patched version (compiled without assertions and debug):\n>\n> Patched event_triggers on: 6.858 ms/7.038 ms/7.434 ms\n> Patched event_triggers off: 6.601 ms/6.958 ms/7.539 ms\n> Master: 6.676 ms/6.697 ms/6.760 ms\n>\n> This is all quite unscientific with a lot of jitter so grains of salt are to be\n> applied, but I find it odd that you don't see any measurable effect. Are you\n> seeing the same/similar connection times between master and with this patch\n> applied?\n\nThank you for doing experiments on your side. I've rechecked. It\nappears that I didn't do enough runs, thus I didn't see the overhead\nas more than an error. Now, I also can confirm ~5% overhead.\n\nI spent some time thinking about how to overcome this overhead, but I\ndidn't find a brilliant option. Previously pg_database flag was\nproposed but then criticized as complex and error-prone. I can also\nimagine shmem caching mechanism. But it would require overcoming\npossible race conditions between shared cache invalidation and\ntransaction commit etc. So, that would be also complex and\nerror-prone. Any better ideas?\n\n> A few small comments on the patch:\n>\n> + prevent successful login to the system. Such bugs may be fixed by\n> + restarting the system in single-user mode (as event triggers are\n> This paragraph should be reworded to recommend the GUC instead of single-user\n> mode (while retaining mention of single-user mode, just not as the primary\n> option).\n>\n>\n> + Also, it's recommended to evade long-running queries in\n> s/evade/avoid/ perhaps?\n\nFixed.\n\n> Thanks for working on this!\n\nThank you as well!\n\n------\nRegards,\nAlexander Korotkov", "msg_date": "Sat, 30 Sep 2023 11:40:23 +0300", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Sorry to have gone dark on this for a long time after having been\nasked for my input back in March. I'm not having a great time trying\nto keep up with email, and the threads getting split up makes it a lot\nworse for me.\n\nOn Fri, Sep 29, 2023 at 6:15 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n> Running the same pgbench command on my laptop looking at the average connection\n> times, and the averaging that over five runs (low/avg/high) I see ~5% increase\n> over master with the patched version (compiled without assertions and debug):\n>\n> Patched event_triggers on: 6.858 ms/7.038 ms/7.434 ms\n> Patched event_triggers off: 6.601 ms/6.958 ms/7.539 ms\n> Master: 6.676 ms/6.697 ms/6.760 ms\n\nThis seems kind of crazy to me. Why does it happen? It sounds to me\nlike we must be doing a lot of extra catalog access to find out\nwhether there are any on-login event triggers. Like maybe a sequential\nscan of pg_event_trigger. Maybe we need to engineer a way to avoid\nthat. I don't have a brilliant idea off-hand, but I feel like there\nshould be something we can do. I think a lot of users would say that\nlogins on PostgreSQL are too slow already.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 2 Oct 2023 14:10:46 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 2 Oct 2023, at 20:10, Robert Haas <robertmhaas@gmail.com> wrote:\n> \n> Sorry to have gone dark on this for a long time after having been\n> asked for my input back in March. I'm not having a great time trying\n> to keep up with email, and the threads getting split up makes it a lot\n> worse for me.\n\nNot a problem, thanks for chiming in.\n\n> On Fri, Sep 29, 2023 at 6:15 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n>> Running the same pgbench command on my laptop looking at the average connection\n>> times, and the averaging that over five runs (low/avg/high) I see ~5% increase\n>> over master with the patched version (compiled without assertions and debug):\n>> \n>> Patched event_triggers on: 6.858 ms/7.038 ms/7.434 ms\n>> Patched event_triggers off: 6.601 ms/6.958 ms/7.539 ms\n>> Master: 6.676 ms/6.697 ms/6.760 ms\n> \n> This seems kind of crazy to me. Why does it happen? It sounds to me\n> like we must be doing a lot of extra catalog access to find out\n> whether there are any on-login event triggers. Like maybe a sequential\n> scan of pg_event_trigger.\n\nThat's exactly what happens, the patch is using BuildEventTriggerCache() to\nbuild the hash for EVT which is then checked for login triggers. This is\nclearly the bottleneck and there needs to be a fast-path. There used to be a\ncache flag in an earlier version of the patch but it was a but klugy, a version\nof that needs to be reimplemented for this patch to fly.\n\n> I think a lot of users would say that logins on PostgreSQL are too slow already.\n\nAgreed.\n\n--\nDaniel Gustafsson\n\n\n\n", "msg_date": "Tue, 3 Oct 2023 15:43:38 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Tue, Oct 3, 2023 at 9:43 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n> That's exactly what happens, the patch is using BuildEventTriggerCache() to\n> build the hash for EVT which is then checked for login triggers. This is\n> clearly the bottleneck and there needs to be a fast-path. There used to be a\n> cache flag in an earlier version of the patch but it was a but klugy, a version\n> of that needs to be reimplemented for this patch to fly.\n\nSo I haven't looked at this patch, but we basically saying that only\nthe superuser can create login triggers, and if they do, those\ntriggers apply to every single user on the system? That would seem to\nbe the logical extension of the existing event trigger mechanism, but\nit isn't obviously as good of a fit for this case as it is for other\ncases where event triggers are a thing.\n\nChanging the catalog representation could be a way around this. What\nif you only allowed one login trigger per database, and instead of\nbeing stored in pg_event_trigger, the OID of the function gets\nrecorded in the pg_database row? Then this would be a lot cheaper\nsince we have to fetch the pg_database row anyway. Or change the SQL\nsyntax to something entirely new so you can have different login\ntriggers for different users -- and maybe users are allowed to create\ntheir own -- but the relevant ones can be found by an index scan\ninstead of a sequential scan.\n\nI'm just spitballing here. If you think the present design is good and\njust want to try to speed it up, I'm not deeply opposed to that. But\nit's also not obvious to me how to stick a cache in front of something\nthat's basically a full-table scan.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 3 Oct 2023 10:21:28 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi, Robert!\n\nOn Tue, Oct 3, 2023 at 5:21 PM Robert Haas <robertmhaas@gmail.com> wrote:\n> On Tue, Oct 3, 2023 at 9:43 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n> > That's exactly what happens, the patch is using BuildEventTriggerCache() to\n> > build the hash for EVT which is then checked for login triggers. This is\n> > clearly the bottleneck and there needs to be a fast-path. There used to be a\n> > cache flag in an earlier version of the patch but it was a but klugy, a version\n> > of that needs to be reimplemented for this patch to fly.\n>\n> So I haven't looked at this patch, but we basically saying that only\n> the superuser can create login triggers, and if they do, those\n> triggers apply to every single user on the system? That would seem to\n> be the logical extension of the existing event trigger mechanism, but\n> it isn't obviously as good of a fit for this case as it is for other\n> cases where event triggers are a thing.\n>\n> Changing the catalog representation could be a way around this. What\n> if you only allowed one login trigger per database, and instead of\n> being stored in pg_event_trigger, the OID of the function gets\n> recorded in the pg_database row? Then this would be a lot cheaper\n> since we have to fetch the pg_database row anyway. Or change the SQL\n> syntax to something entirely new so you can have different login\n> triggers for different users -- and maybe users are allowed to create\n> their own -- but the relevant ones can be found by an index scan\n> instead of a sequential scan.\n>\n> I'm just spitballing here. If you think the present design is good and\n> just want to try to speed it up, I'm not deeply opposed to that. But\n> it's also not obvious to me how to stick a cache in front of something\n> that's basically a full-table scan.\n\nThank you for the interesting ideas. I'd like to try to revive the\nversion with the flag in pg_database. Will use other ideas as backup\nif no success.\n\n------\nRegards,\nAlexander Korotkov\n\n\n", "msg_date": "Tue, 3 Oct 2023 20:35:57 +0300", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi!\n\nOn Tue, Oct 3, 2023 at 8:35 PM Alexander Korotkov <aekorotkov@gmail.com> wrote:\n> Thank you for the interesting ideas. I'd like to try to revive the\n> version with the flag in pg_database. Will use other ideas as backup\n> if no success.\n\nI've revived the patch version with pg_database.dathasloginevt flag.\nI took v32 version [1] and made the following changes.\n\n * Incorporate enchantments made on flagless version of patch.\n * Read dathasloginevt during InitPostgres() to prevent extra catalog\naccess and even more notable StartTransactionCommand() when there are\nno login triggers.\n * Hold lock during setting of pg_database.dathasloginevt flag (v32\nversion actually didn't prevent race condition).\n * Fix AlterEventTrigger() to check event name not trigger name\n * Acquire conditional lock while resetting pg_database.dathasloginevt\nflag to prevent new database connection to hang waiting another\ntransaction to finish.\n\nThis version should be good and has no overhead. Any thoughts?\nDaniel, could you please re-run the performance tests?\n\nLinks\n1. https://www.postgresql.org/message-id/CAMEv5_vDjceLr54WUCNPPVsJs8WBWWsRW826VppNEFoLC1LAEw%40mail.gmail.com\n\n------\nRegards,\nAlexander Korotkov\n\n\n", "msg_date": "Mon, 9 Oct 2023 17:11:25 +0300", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On 2023-10-09 17:11:25 +0300, Alexander Korotkov wrote:\n> This version should be good and has no overhead. Any thoughts?\n\nI think you forgot to attach the patch?\n\n\n", "msg_date": "Mon, 9 Oct 2023 13:58:31 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Mon, Oct 9, 2023 at 11:58 PM Andres Freund <andres@anarazel.de> wrote:\n> On 2023-10-09 17:11:25 +0300, Alexander Korotkov wrote:\n> > This version should be good and has no overhead. Any thoughts?\n>\n> I think you forgot to attach the patch?\n\nThat's it!\n\n------\nRegards,\nAlexander Korotkov", "msg_date": "Tue, 10 Oct 2023 08:18:46 +0300", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Mon, Oct 9, 2023 at 10:11 AM Alexander Korotkov <aekorotkov@gmail.com> wrote:\n> * Hold lock during setting of pg_database.dathasloginevt flag (v32\n> version actually didn't prevent race condition).\n\nSo ... how does getting this flag set actually work? And how does\nclearing it work?\n\nIn the case of row-level security, you have to explicitly enable the\nflag on the table level using DDL provided for that purpose. In the\ncase of relhas{rules,triggers,subclass} the flag is set automatically\nas a side-effect of some other operation. I tend to consider that the\nlatter design is somewhat messy. It's potentially even messier here,\nbecause at least when you add a rule or a trigger to a table you're\nexpecting to take a lock on the table anyway. I don't think you\nnecessarily expect creating a login trigger to take a lock on the\ndatabase. That's a bit odd and could have visible side effects. And if\nyou don't, then what happens is that if you create two login triggers\nin overlapping transactions, then (1) if there were no login triggers\npreviously, one of the transactions fails with an internal-looking\nerror message about a concurrent tuple update and (2) if there were\nlogin triggers previously, then it works fine. That's also a bit weird\nand surprising. Now the counter-argument could be that adding new DDL\nto enable login triggers for a database is too much cognitive burden\nand it's better to have the kind of weird and surprising behavior that\nI just discussed. I don't know that I would buy that argument, but it\ncould be made ... and my real point here is that I don't even see\nthese trade-offs being discussed. Apologies if they were discussed\nearlier and I just missed that; I confess to not having read every\nemail message on this topic, and some of the ones I did read I read a\nlong time ago.\n\n> This version should be good and has no overhead. Any thoughts?\n> Daniel, could you please re-run the performance tests?\n\nIs \"no overhead\" an overly bold claim here?\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 10 Oct 2023 10:50:55 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi,\n\nOn 2023-10-10 08:18:46 +0300, Alexander Korotkov wrote:\n> @@ -968,7 +969,7 @@ createdb(ParseState *pstate, const CreatedbStmt *stmt)\n> \n> \tif (!get_db_info(dbtemplate, ShareLock,\n> \t\t\t\t\t &src_dboid, &src_owner, &src_encoding,\n> -\t\t\t\t\t &src_istemplate, &src_allowconn,\n> +\t\t\t\t\t &src_istemplate, &src_allowconn, &src_hasloginevt,\n> \t\t\t\t\t &src_frozenxid, &src_minmxid, &src_deftablespace,\n> \t\t\t\t\t &src_collate, &src_ctype, &src_iculocale, &src_icurules, &src_locprovider,\n> \t\t\t\t\t &src_collversion))\n\nThis isn't your fault, but this imo has become unreadable. Think we ought to\nmove the information about a database to a struct.\n\n\n> @@ -296,6 +306,13 @@ insert_event_trigger_tuple(const char *trigname, const char *eventname, Oid evtO\n> \tCatalogTupleInsert(tgrel, tuple);\n> \theap_freetuple(tuple);\n> \n> +\t/*\n> +\t * Login event triggers have an additional flag in pg_database to allow\n> +\t * faster lookups in hot codepaths. Set the flag unless already True.\n> +\t */\n> +\tif (strcmp(eventname, \"login\") == 0)\n> +\t\tSetDatatabaseHasLoginEventTriggers();\n\nIt's not really faster lookups, it's no lookups, right?\n\n\n> \t/* Depend on owner. */\n> \trecordDependencyOnOwner(EventTriggerRelationId, trigoid, evtOwner);\n> \n> @@ -357,6 +374,39 @@ filter_list_to_array(List *filterlist)\n> \treturn PointerGetDatum(construct_array_builtin(data, l, TEXTOID));\n> }\n> \n> +/*\n> + * Set pg_database.dathasloginevt flag for current database indicating that\n> + * current database has on login triggers.\n> + */\n> +void\n> +SetDatatabaseHasLoginEventTriggers(void)\n> +{\n> +\t/* Set dathasloginevt flag in pg_database */\n> +\tForm_pg_database db;\n> +\tRelation\tpg_db = table_open(DatabaseRelationId, RowExclusiveLock);\n> +\tHeapTuple\ttuple;\n> +\n> +\t/*\n> +\t * Use shared lock to prevent a conflit with EventTriggerOnLogin() trying\n> +\t * to reset pg_database.dathasloginevt flag. Note that we use\n> +\t * AccessShareLock allowing setters concurently.\n> +\t */\n> +\tLockSharedObject(DatabaseRelationId, MyDatabaseId, 0, AccessShareLock);\n\nThat seems like a very odd approach - how does this avoid concurrency issues\nwith one backend setting and another unsetting the flag? And outside of that,\nwon't this just lead to concurrently updated tuples?\n\n\n> +\ttuple = SearchSysCacheCopy1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));\n> +\tif (!HeapTupleIsValid(tuple))\n> +\t\telog(ERROR, \"cache lookup failed for database %u\", MyDatabaseId);\n> +\tdb = (Form_pg_database) GETSTRUCT(tuple);\n> +\tif (!db->dathasloginevt)\n> +\t{\n> +\t\tdb->dathasloginevt = true;\n> +\t\tCatalogTupleUpdate(pg_db, &tuple->t_self, tuple);\n> +\t\tCommandCounterIncrement();\n> +\t}\n> +\ttable_close(pg_db, RowExclusiveLock);\n> +\theap_freetuple(tuple);\n> +}\n> +\n> /*\n> * ALTER EVENT TRIGGER foo ENABLE|DISABLE|ENABLE ALWAYS|REPLICA\n> */\n> @@ -391,6 +441,10 @@ AlterEventTrigger(AlterEventTrigStmt *stmt)\n> \n> \tCatalogTupleUpdate(tgrel, &tup->t_self, tup);\n> \n> +\tif (namestrcmp(&evtForm->evtevent, \"login\") == 0 &&\n> +\t\ttgenabled != TRIGGER_DISABLED)\n> +\t\tSetDatatabaseHasLoginEventTriggers();\n> +\n> \tInvokeObjectPostAlterHook(EventTriggerRelationId,\n> \t\t\t\t\t\t\t trigoid, 0);\n> \n> @@ -557,7 +611,7 @@ filter_event_trigger(CommandTag tag, EventTriggerCacheItem *item)\n> static List *\n> EventTriggerCommonSetup(Node *parsetree,\n> \t\t\t\t\t\tEventTriggerEvent event, const char *eventstr,\n> -\t\t\t\t\t\tEventTriggerData *trigdata)\n> +\t\t\t\t\t\tEventTriggerData *trigdata, bool unfiltered)\n> {\n> \tCommandTag\ttag;\n> \tList\t *cachelist;\n> @@ -582,10 +636,15 @@ EventTriggerCommonSetup(Node *parsetree,\n> \t{\n> \t\tCommandTag\tdbgtag;\n> \n> -\t\tdbgtag = CreateCommandTag(parsetree);\n> +\t\tif (event == EVT_Login)\n> +\t\t\tdbgtag = CMDTAG_LOGIN;\n> +\t\telse\n> +\t\t\tdbgtag = CreateCommandTag(parsetree);\n> +\n> \t\tif (event == EVT_DDLCommandStart ||\n> \t\t\tevent == EVT_DDLCommandEnd ||\n> -\t\t\tevent == EVT_SQLDrop)\n> +\t\t\tevent == EVT_SQLDrop ||\n> +\t\t\tevent == EVT_Login)\n> \t\t{\n> \t\t\tif (!command_tag_event_trigger_ok(dbgtag))\n> \t\t\t\telog(ERROR, \"unexpected command tag \\\"%s\\\"\", GetCommandTagName(dbgtag));\n> @@ -604,7 +663,10 @@ EventTriggerCommonSetup(Node *parsetree,\n> \t\treturn NIL;\n> \n> \t/* Get the command tag. */\n> -\ttag = CreateCommandTag(parsetree);\n> +\tif (event == EVT_Login)\n> +\t\ttag = CMDTAG_LOGIN;\n> +\telse\n> +\t\ttag = CreateCommandTag(parsetree);\n\nSeems this bit should instead be in a function, given that you have it in\nmultiple places.\n\n\n> \n> +/*\n> + * Fire login event triggers if any are present. The dathasloginevt\n> + * pg_database flag is left when an event trigger is dropped, to avoid\n> + * complicating the codepath in the case of multiple event triggers. This\n> + * function will instead unset the flag if no trigger is defined.\n> + */\n> +void\n> +EventTriggerOnLogin(void)\n> +{\n> +\tList\t *runlist;\n> +\tEventTriggerData trigdata;\n> +\n> +\t/*\n> +\t * See EventTriggerDDLCommandStart for a discussion about why event\n> +\t * triggers are disabled in single user mode or via a GUC. We also need a\n> +\t * database connection (some background workers doesn't have it).\n> +\t */\n> +\tif (!IsUnderPostmaster || !event_triggers ||\n> +\t\t!OidIsValid(MyDatabaseId) || !MyDatabaseHasLoginEventTriggers)\n> +\t\treturn;\n> +\n> +\tStartTransactionCommand();\n> +\trunlist = EventTriggerCommonSetup(NULL,\n> +\t\t\t\t\t\t\t\t\t\tEVT_Login, \"login\",\n> +\t\t\t\t\t\t\t\t\t\t&trigdata, false);\n> +\n> +\tif (runlist != NIL)\n> +\t{\n> +\t\t/*\n> +\t\t * Event trigger execution may require an active snapshot.\n> +\t\t */\n> +\t\tPushActiveSnapshot(GetTransactionSnapshot());\n> +\n> +\t\t/* Run the triggers. */\n> +\t\tEventTriggerInvoke(runlist, &trigdata);\n> +\n> +\t\t/* Cleanup. */\n> +\t\tlist_free(runlist);\n> +\n> +\t\tPopActiveSnapshot();\n> +\t}\n> +\t/*\n> +\t * There is no active login event trigger, but our pg_database.dathasloginevt was set.\n> +\t * Try to unset this flag. We use the lock to prevent concurrent\n> +\t * SetDatatabaseHasLoginEventTriggers(), but we don't want to hang the\n> +\t * connection waiting on the lock. Thus, we are just trying to acquire\n> +\t * the lock conditionally.\n> +\t */\n> +\telse if (ConditionalLockSharedObject(DatabaseRelationId, MyDatabaseId,\n> +\t\t\t\t\t\t\t\t\t\t 0, AccessExclusiveLock))\n\nEek. Why are we doing it this way? I think this is a seriously bad\nidea. Maybe it's obvious to you, but it seems much more reasonable to make the\npg_database column an integer and count the number of login event\ntriggers. When 0, then we don't need to look for login event triggers.\n\n\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 10 Oct 2023 09:37:30 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi!\n\nThank you for the review.\n\nOn Tue, Oct 10, 2023 at 7:37 PM Andres Freund <andres@anarazel.de> wrote:\n> On 2023-10-10 08:18:46 +0300, Alexander Korotkov wrote:\n> > @@ -968,7 +969,7 @@ createdb(ParseState *pstate, const CreatedbStmt *stmt)\n> >\n> > if (!get_db_info(dbtemplate, ShareLock,\n> > &src_dboid, &src_owner, &src_encoding,\n> > - &src_istemplate, &src_allowconn,\n> > + &src_istemplate, &src_allowconn, &src_hasloginevt,\n> > &src_frozenxid, &src_minmxid, &src_deftablespace,\n> > &src_collate, &src_ctype, &src_iculocale, &src_icurules, &src_locprovider,\n> > &src_collversion))\n>\n> This isn't your fault, but this imo has become unreadable. Think we ought to\n> move the information about a database to a struct.\n\nShould I do this in a separate patch?\n\n> > @@ -296,6 +306,13 @@ insert_event_trigger_tuple(const char *trigname, const char *eventname, Oid evtO\n> > CatalogTupleInsert(tgrel, tuple);\n> > heap_freetuple(tuple);\n> >\n> > + /*\n> > + * Login event triggers have an additional flag in pg_database to allow\n> > + * faster lookups in hot codepaths. Set the flag unless already True.\n> > + */\n> > + if (strcmp(eventname, \"login\") == 0)\n> > + SetDatatabaseHasLoginEventTriggers();\n>\n> It's not really faster lookups, it's no lookups, right?\n\nYes, no extra lookups. Fixed.\n\n> > /* Depend on owner. */\n> > recordDependencyOnOwner(EventTriggerRelationId, trigoid, evtOwner);\n> >\n> > @@ -357,6 +374,39 @@ filter_list_to_array(List *filterlist)\n> > return PointerGetDatum(construct_array_builtin(data, l, TEXTOID));\n> > }\n> >\n> > +/*\n> > + * Set pg_database.dathasloginevt flag for current database indicating that\n> > + * current database has on login triggers.\n> > + */\n> > +void\n> > +SetDatatabaseHasLoginEventTriggers(void)\n> > +{\n> > + /* Set dathasloginevt flag in pg_database */\n> > + Form_pg_database db;\n> > + Relation pg_db = table_open(DatabaseRelationId, RowExclusiveLock);\n> > + HeapTuple tuple;\n> > +\n> > + /*\n> > + * Use shared lock to prevent a conflit with EventTriggerOnLogin() trying\n> > + * to reset pg_database.dathasloginevt flag. Note that we use\n> > + * AccessShareLock allowing setters concurently.\n> > + */\n> > + LockSharedObject(DatabaseRelationId, MyDatabaseId, 0, AccessShareLock);\n>\n> That seems like a very odd approach - how does this avoid concurrency issues\n> with one backend setting and another unsetting the flag? And outside of that,\n> won't this just lead to concurrently updated tuples?\n\nWhen backend unsets the flag, it acquires the lock first. If lock is\nacquired successfully then no other backends hold it. If the\nconcurrent backend have already inserted an event trigger then we will\ndetect it by rechecking event list under lock. If the concurrent\nbackend inserted/enabled event trigger and waiting for the lock, then\nit will set the flag once we release the lock.\n\n> > + tuple = SearchSysCacheCopy1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));\n> > + if (!HeapTupleIsValid(tuple))\n> > + elog(ERROR, \"cache lookup failed for database %u\", MyDatabaseId);\n> > + db = (Form_pg_database) GETSTRUCT(tuple);\n> > + if (!db->dathasloginevt)\n> > + {\n> > + db->dathasloginevt = true;\n> > + CatalogTupleUpdate(pg_db, &tuple->t_self, tuple);\n> > + CommandCounterIncrement();\n> > + }\n> > + table_close(pg_db, RowExclusiveLock);\n> > + heap_freetuple(tuple);\n> > +}\n> > +\n> > /*\n> > * ALTER EVENT TRIGGER foo ENABLE|DISABLE|ENABLE ALWAYS|REPLICA\n> > */\n> > @@ -391,6 +441,10 @@ AlterEventTrigger(AlterEventTrigStmt *stmt)\n> >\n> > CatalogTupleUpdate(tgrel, &tup->t_self, tup);\n> >\n> > + if (namestrcmp(&evtForm->evtevent, \"login\") == 0 &&\n> > + tgenabled != TRIGGER_DISABLED)\n> > + SetDatatabaseHasLoginEventTriggers();\n> > +\n> > InvokeObjectPostAlterHook(EventTriggerRelationId,\n> > trigoid, 0);\n> >\n> > @@ -557,7 +611,7 @@ filter_event_trigger(CommandTag tag, EventTriggerCacheItem *item)\n> > static List *\n> > EventTriggerCommonSetup(Node *parsetree,\n> > EventTriggerEvent event, const char *eventstr,\n> > - EventTriggerData *trigdata)\n> > + EventTriggerData *trigdata, bool unfiltered)\n> > {\n> > CommandTag tag;\n> > List *cachelist;\n> > @@ -582,10 +636,15 @@ EventTriggerCommonSetup(Node *parsetree,\n> > {\n> > CommandTag dbgtag;\n> >\n> > - dbgtag = CreateCommandTag(parsetree);\n> > + if (event == EVT_Login)\n> > + dbgtag = CMDTAG_LOGIN;\n> > + else\n> > + dbgtag = CreateCommandTag(parsetree);\n> > +\n> > if (event == EVT_DDLCommandStart ||\n> > event == EVT_DDLCommandEnd ||\n> > - event == EVT_SQLDrop)\n> > + event == EVT_SQLDrop ||\n> > + event == EVT_Login)\n> > {\n> > if (!command_tag_event_trigger_ok(dbgtag))\n> > elog(ERROR, \"unexpected command tag \\\"%s\\\"\", GetCommandTagName(dbgtag));\n> > @@ -604,7 +663,10 @@ EventTriggerCommonSetup(Node *parsetree,\n> > return NIL;\n> >\n> > /* Get the command tag. */\n> > - tag = CreateCommandTag(parsetree);\n> > + if (event == EVT_Login)\n> > + tag = CMDTAG_LOGIN;\n> > + else\n> > + tag = CreateCommandTag(parsetree);\n>\n> Seems this bit should instead be in a function, given that you have it in\n> multiple places.\n\nDone.\n\n> > +/*\n> > + * Fire login event triggers if any are present. The dathasloginevt\n> > + * pg_database flag is left when an event trigger is dropped, to avoid\n> > + * complicating the codepath in the case of multiple event triggers. This\n> > + * function will instead unset the flag if no trigger is defined.\n> > + */\n> > +void\n> > +EventTriggerOnLogin(void)\n> > +{\n> > + List *runlist;\n> > + EventTriggerData trigdata;\n> > +\n> > + /*\n> > + * See EventTriggerDDLCommandStart for a discussion about why event\n> > + * triggers are disabled in single user mode or via a GUC. We also need a\n> > + * database connection (some background workers doesn't have it).\n> > + */\n> > + if (!IsUnderPostmaster || !event_triggers ||\n> > + !OidIsValid(MyDatabaseId) || !MyDatabaseHasLoginEventTriggers)\n> > + return;\n> > +\n> > + StartTransactionCommand();\n> > + runlist = EventTriggerCommonSetup(NULL,\n> > + EVT_Login, \"login\",\n> > + &trigdata, false);\n> > +\n> > + if (runlist != NIL)\n> > + {\n> > + /*\n> > + * Event trigger execution may require an active snapshot.\n> > + */\n> > + PushActiveSnapshot(GetTransactionSnapshot());\n> > +\n> > + /* Run the triggers. */\n> > + EventTriggerInvoke(runlist, &trigdata);\n> > +\n> > + /* Cleanup. */\n> > + list_free(runlist);\n> > +\n> > + PopActiveSnapshot();\n> > + }\n> > + /*\n> > + * There is no active login event trigger, but our pg_database.dathasloginevt was set.\n> > + * Try to unset this flag. We use the lock to prevent concurrent\n> > + * SetDatatabaseHasLoginEventTriggers(), but we don't want to hang the\n> > + * connection waiting on the lock. Thus, we are just trying to acquire\n> > + * the lock conditionally.\n> > + */\n> > + else if (ConditionalLockSharedObject(DatabaseRelationId, MyDatabaseId,\n> > + 0, AccessExclusiveLock))\n>\n> Eek. Why are we doing it this way? I think this is a seriously bad\n> idea. Maybe it's obvious to you, but it seems much more reasonable to make the\n> pg_database column an integer and count the number of login event\n> triggers. When 0, then we don't need to look for login event triggers.\n\nThe approach with number of login event trigger obviously will also\nwork. But this version with lazy flag cleaning avoids need to handle\nevery unobvious case we delete the event triggers (cascading deletion\netc).\n\n------\nRegards,\nAlexander Korotkov", "msg_date": "Tue, 10 Oct 2023 22:32:52 +0300", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi, Robert!\n\nThank you for your feedback.\n\nOn Tue, Oct 10, 2023 at 5:51 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n> On Mon, Oct 9, 2023 at 10:11 AM Alexander Korotkov <aekorotkov@gmail.com> wrote:\n> > * Hold lock during setting of pg_database.dathasloginevt flag (v32\n> > version actually didn't prevent race condition).\n>\n> So ... how does getting this flag set actually work? And how does\n> clearing it work?\n\nI hope I explained that in [1].\n\n> In the case of row-level security, you have to explicitly enable the\n> flag on the table level using DDL provided for that purpose. In the\n> case of relhas{rules,triggers,subclass} the flag is set automatically\n> as a side-effect of some other operation. I tend to consider that the\n> latter design is somewhat messy. It's potentially even messier here,\n> because at least when you add a rule or a trigger to a table you're\n> expecting to take a lock on the table anyway. I don't think you\n> necessarily expect creating a login trigger to take a lock on the\n> database. That's a bit odd and could have visible side effects. And if\n> you don't, then what happens is that if you create two login triggers\n> in overlapping transactions, then (1) if there were no login triggers\n> previously, one of the transactions fails with an internal-looking\n> error message about a concurrent tuple update and (2) if there were\n> login triggers previously, then it works fine.\n\nYep, in v43 it worked that way. One transaction has to wait for\nanother finishing update of pg_database tuple, then fails. This is\nobviously ridiculous. Since overlapping setters of flag will have to\nwait anyway, I changed lock mode in v44 for them to\nAccessExclusiveLock. Now, waiting transaction then sees the updated\ntuple and doesn't fail.\n\n> That's also a bit weird\n> and surprising. Now the counter-argument could be that adding new DDL\n> to enable login triggers for a database is too much cognitive burden\n> and it's better to have the kind of weird and surprising behavior that\n> I just discussed. I don't know that I would buy that argument, but it\n> could be made ... and my real point here is that I don't even see\n> these trade-offs being discussed. Apologies if they were discussed\n> earlier and I just missed that; I confess to not having read every\n> email message on this topic, and some of the ones I did read I read a\n> long time ago.\n\nI have read the thread quite carefully. I don't think manual setting\nof the flag was discussed. I do think it would be extra burden for\nusers, and I would prefer automatic flag as long as it works\ntransparently and reliably.\n\n> > This version should be good and has no overhead. Any thoughts?\n> > Daniel, could you please re-run the performance tests?\n>\n> Is \"no overhead\" an overly bold claim here?\n\nYes, sure. I meant no extra lookup. Hopefully that would mean no\nmeasurable overhead when is no enabled login triggers.\n\nLinks\n1. https://www.postgresql.org/message-id/CAPpHfdtvvozi%3Dttp8kvJQwuLrP5Q0D_5c4Pw1U67MRXcROB9yA%40mail.gmail.com\n\n------\nRegards,\nAlexander Korotkov\n\n\n", "msg_date": "Tue, 10 Oct 2023 22:43:05 +0300", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Tue, Oct 10, 2023 at 3:43 PM Alexander Korotkov <aekorotkov@gmail.com> wrote:\n> Yep, in v43 it worked that way. One transaction has to wait for\n> another finishing update of pg_database tuple, then fails. This is\n> obviously ridiculous. Since overlapping setters of flag will have to\n> wait anyway, I changed lock mode in v44 for them to\n> AccessExclusiveLock. Now, waiting transaction then sees the updated\n> tuple and doesn't fail.\n\nDoesn't that mean that if you create the first login trigger in a\ndatabase and leave the transaction open, nobody can connect to that\ndatabase until the transaction ends?\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 12 Oct 2023 13:34:57 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Thu, Oct 12, 2023 at 8:35 PM Robert Haas <robertmhaas@gmail.com> wrote:\n> On Tue, Oct 10, 2023 at 3:43 PM Alexander Korotkov <aekorotkov@gmail.com> wrote:\n> > Yep, in v43 it worked that way. One transaction has to wait for\n> > another finishing update of pg_database tuple, then fails. This is\n> > obviously ridiculous. Since overlapping setters of flag will have to\n> > wait anyway, I changed lock mode in v44 for them to\n> > AccessExclusiveLock. Now, waiting transaction then sees the updated\n> > tuple and doesn't fail.\n>\n> Doesn't that mean that if you create the first login trigger in a\n> database and leave the transaction open, nobody can connect to that\n> database until the transaction ends?\n\nIt doesn't mean that, because when trying to reset the flag v44 does\nconditional lock. So, if another transaction is holding the log we\nwill just skip resetting the flag. So, the flag will be cleared on\nthe first connection after that transaction ends.\n\n------\nRegards,\nAlexander Korotkov\n\n\n", "msg_date": "Fri, 13 Oct 2023 01:54:01 +0300", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Thu, Oct 12, 2023 at 6:54 PM Alexander Korotkov <aekorotkov@gmail.com> wrote:\n> On Thu, Oct 12, 2023 at 8:35 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> > Doesn't that mean that if you create the first login trigger in a\n> > database and leave the transaction open, nobody can connect to that\n> > database until the transaction ends?\n>\n> It doesn't mean that, because when trying to reset the flag v44 does\n> conditional lock. So, if another transaction is holding the log we\n> will just skip resetting the flag. So, the flag will be cleared on\n> the first connection after that transaction ends.\n\nBut in the scenario I am describing the flag is being set, not reset.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 12 Oct 2023 21:18:23 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Fri, Oct 13, 2023 at 4:18 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> On Thu, Oct 12, 2023 at 6:54 PM Alexander Korotkov <aekorotkov@gmail.com> wrote:\n> > On Thu, Oct 12, 2023 at 8:35 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n> > > Doesn't that mean that if you create the first login trigger in a\n> > > database and leave the transaction open, nobody can connect to that\n> > > database until the transaction ends?\n> >\n> > It doesn't mean that, because when trying to reset the flag v44 does\n> > conditional lock. So, if another transaction is holding the log we\n> > will just skip resetting the flag. So, the flag will be cleared on\n> > the first connection after that transaction ends.\n>\n> But in the scenario I am describing the flag is being set, not reset.\n\nSorry, it seems I just missed some logical steps. Imagine, that\ntransaction A created the first login trigger and hangs open. Then\nthe new connection B sees no visible triggers yet, but dathasloginevt\nflag is set. Therefore, connection B tries conditional lock but just\ngives up because the lock is held by transaction A.\n\nAlso, note that the lock has been just some lock with a custom tag.\nIt doesn't effectively block the database. You may think about it as\nof custom advisory lock.\n\n------\nRegards,\nAlexander Korotkov\n\n\n", "msg_date": "Fri, 13 Oct 2023 11:26:45 +0300", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Fri, Oct 13, 2023 at 11:26 AM Alexander Korotkov\n<aekorotkov@gmail.com> wrote:\n> On Fri, Oct 13, 2023 at 4:18 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> > On Thu, Oct 12, 2023 at 6:54 PM Alexander Korotkov <aekorotkov@gmail.com> wrote:\n> > > On Thu, Oct 12, 2023 at 8:35 PM Robert Haas <robertmhaas@gmail.com> wrote:\n> >\n> > > > Doesn't that mean that if you create the first login trigger in a\n> > > > database and leave the transaction open, nobody can connect to that\n> > > > database until the transaction ends?\n> > >\n> > > It doesn't mean that, because when trying to reset the flag v44 does\n> > > conditional lock. So, if another transaction is holding the log we\n> > > will just skip resetting the flag. So, the flag will be cleared on\n> > > the first connection after that transaction ends.\n> >\n> > But in the scenario I am describing the flag is being set, not reset.\n>\n> Sorry, it seems I just missed some logical steps. Imagine, that\n> transaction A created the first login trigger and hangs open. Then\n> the new connection B sees no visible triggers yet, but dathasloginevt\n> flag is set. Therefore, connection B tries conditional lock but just\n> gives up because the lock is held by transaction A.\n>\n> Also, note that the lock has been just some lock with a custom tag.\n> It doesn't effectively block the database. You may think about it as\n> of custom advisory lock.\n\nI've revised the comments about the lock a bit. I've also run some\ntests regarding the connection time (5 runs).\n\nv45, event_triggers=on: avg=3.081ms, min=2.992ms, max=3.146ms\nv45, event_triggers=off: avg=3.132ms, min=3.048ms, max=3.186ms\nmaster: 3.080ms, min=3.023ms, max=3.167ms\n\nSo, no measurable overhead (not surprising since no extra catalog lookup).\nI think this patch is in the commitable shape. Any objections?\n\n------\nRegards,\nAlexander Korotkov", "msg_date": "Sat, 14 Oct 2023 02:10:33 +0300", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Sat, Oct 14, 2023 at 2:10 AM Alexander Korotkov <aekorotkov@gmail.com> wrote:\n> On Fri, Oct 13, 2023 at 11:26 AM Alexander Korotkov\n> <aekorotkov@gmail.com> wrote:\n> > On Fri, Oct 13, 2023 at 4:18 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> > > On Thu, Oct 12, 2023 at 6:54 PM Alexander Korotkov <aekorotkov@gmail.com> wrote:\n> > > > On Thu, Oct 12, 2023 at 8:35 PM Robert Haas <robertmhaas@gmail.com> wrote:\n> > >\n> > > > > Doesn't that mean that if you create the first login trigger in a\n> > > > > database and leave the transaction open, nobody can connect to that\n> > > > > database until the transaction ends?\n> > > >\n> > > > It doesn't mean that, because when trying to reset the flag v44 does\n> > > > conditional lock. So, if another transaction is holding the log we\n> > > > will just skip resetting the flag. So, the flag will be cleared on\n> > > > the first connection after that transaction ends.\n> > >\n> > > But in the scenario I am describing the flag is being set, not reset.\n> >\n> > Sorry, it seems I just missed some logical steps. Imagine, that\n> > transaction A created the first login trigger and hangs open. Then\n> > the new connection B sees no visible triggers yet, but dathasloginevt\n> > flag is set. Therefore, connection B tries conditional lock but just\n> > gives up because the lock is held by transaction A.\n> >\n> > Also, note that the lock has been just some lock with a custom tag.\n> > It doesn't effectively block the database. You may think about it as\n> > of custom advisory lock.\n>\n> I've revised the comments about the lock a bit. I've also run some\n> tests regarding the connection time (5 runs).\n>\n> v45, event_triggers=on: avg=3.081ms, min=2.992ms, max=3.146ms\n> v45, event_triggers=off: avg=3.132ms, min=3.048ms, max=3.186ms\n> master: 3.080ms, min=3.023ms, max=3.167ms\n>\n> So, no measurable overhead (not surprising since no extra catalog lookup).\n> I think this patch is in the commitable shape. Any objections?\n\nThe attached revision fixes test failures spotted by\ncommitfest.cputube.org. Also, perl scripts passed perltidy.\n\n------\nRegards,\nAlexander Korotkov", "msg_date": "Mon, 16 Oct 2023 02:47:03 +0300", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Mon, Oct 16, 2023 at 02:47:03AM +0300, Alexander Korotkov wrote:\n> The attached revision fixes test failures spotted by\n> commitfest.cputube.org. Also, perl scripts passed perltidy.\n\nStill you've missed a few things. At quick glance:\n- The code indentation was off a bit in event_trigger.c.\n- 005_login_trigger.pl fails if the code is compiled with\nENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS because a WARNING is\nreported in test \"create tmp objects: err equals\".\n- 005_sspi.pl is older than the new test 005_login_trigger.pl, could\nyou rename it with a different number?\n--\nMichael", "msg_date": "Mon, 16 Oct 2023 10:00:39 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Mon, Oct 16, 2023 at 4:00 AM Michael Paquier <michael@paquier.xyz> wrote:\n> On Mon, Oct 16, 2023 at 02:47:03AM +0300, Alexander Korotkov wrote:\n> > The attached revision fixes test failures spotted by\n> > commitfest.cputube.org. Also, perl scripts passed perltidy.\n>\n> Still you've missed a few things. At quick glance:\n> - The code indentation was off a bit in event_trigger.c.\n> - 005_login_trigger.pl fails if the code is compiled with\n> ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS because a WARNING is\n> reported in test \"create tmp objects: err equals\".\n> - 005_sspi.pl is older than the new test 005_login_trigger.pl, could\n> you rename it with a different number?\n\nYou are very fast and sharp eye!\nThank you for fixing the indentation. I just pushed fixes for the rest.\n\n------\nRegards,\nAlexander Korotkov\n\n\n", "msg_date": "Mon, 16 Oct 2023 04:05:08 +0300", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi Alexander,\n\nSorry for my long offline and thanks for the activity. So should we close\nthe patch on the commitfest page now?\n\nBy the way I had one more issue with the login trigger tests (quite a rare\none though). A race condition may occur on some systems, when oidjoins test\nstarts a moment later than normally and affects logins count for on-login\ntrigger test. Thus I had to split event_trigger and oidjoins tests into\nseparate parallel groups. I'll post this as an independent patch then.\n\n--\n best regards,\n Mikhail A. Gribkov\n\ne-mail: youzhick@gmail.com\n*http://www.flickr.com/photos/youzhick/albums\n<http://www.flickr.com/photos/youzhick/albums>*\nhttp://www.strava.com/athletes/5085772\nphone: +7(916)604-71-12\nTelegram: @youzhick\n\n\n\nOn Mon, Oct 16, 2023 at 4:05 AM Alexander Korotkov <aekorotkov@gmail.com>\nwrote:\n\n> On Mon, Oct 16, 2023 at 4:00 AM Michael Paquier <michael@paquier.xyz>\n> wrote:\n> > On Mon, Oct 16, 2023 at 02:47:03AM +0300, Alexander Korotkov wrote:\n> > > The attached revision fixes test failures spotted by\n> > > commitfest.cputube.org. Also, perl scripts passed perltidy.\n> >\n> > Still you've missed a few things. At quick glance:\n> > - The code indentation was off a bit in event_trigger.c.\n> > - 005_login_trigger.pl fails if the code is compiled with\n> > ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS because a WARNING is\n> > reported in test \"create tmp objects: err equals\".\n> > - 005_sspi.pl is older than the new test 005_login_trigger.pl, could\n> > you rename it with a different number?\n>\n> You are very fast and sharp eye!\n> Thank you for fixing the indentation. I just pushed fixes for the rest.\n>\n> ------\n> Regards,\n> Alexander Korotkov\n>\n\nHi Alexander,Sorry for my long offline and thanks for the activity. So should we close the patch on the commitfest page now?By the way I had one more issue with the login trigger tests (quite a rare one though). A race condition may occur on some systems, when oidjoins test starts a moment later than normally and affects logins count for on-login trigger test. Thus I had to split event_trigger and oidjoins tests into separate parallel groups. I'll post this as an independent patch then.-- best regards,    Mikhail A. Gribkove-mail: youzhick@gmail.comhttp://www.flickr.com/photos/youzhick/albumshttp://www.strava.com/athletes/5085772phone: +7(916)604-71-12Telegram: @youzhickOn Mon, Oct 16, 2023 at 4:05 AM Alexander Korotkov <aekorotkov@gmail.com> wrote:On Mon, Oct 16, 2023 at 4:00 AM Michael Paquier <michael@paquier.xyz> wrote:\n> On Mon, Oct 16, 2023 at 02:47:03AM +0300, Alexander Korotkov wrote:\n> > The attached revision fixes test failures spotted by\n> > commitfest.cputube.org.  Also, perl scripts passed perltidy.\n>\n> Still you've missed a few things.  At quick glance:\n> - The code indentation was off a bit in event_trigger.c.\n> - 005_login_trigger.pl fails if the code is compiled with\n> ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS because a WARNING is\n> reported in test \"create tmp objects: err equals\".\n> - 005_sspi.pl is older than the new test 005_login_trigger.pl, could\n> you rename it with a different number?\n\nYou are very fast and sharp eye!\nThank you for fixing the indentation.  I just pushed fixes for the rest.\n\n------\nRegards,\nAlexander Korotkov", "msg_date": "Wed, 18 Oct 2023 13:29:50 +0300", "msg_from": "Mikhail Gribkov <youzhick@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi, Mikhail.\n\nOn Wed, Oct 18, 2023 at 1:30 PM Mikhail Gribkov <youzhick@gmail.com> wrote:\n> Sorry for my long offline and thanks for the activity. So should we close the patch on the commitfest page now?\n\nI have just done this.\n\n> By the way I had one more issue with the login trigger tests (quite a rare one though). A race condition may occur on some systems, when oidjoins test starts a moment later than normally and affects logins count for on-login trigger test. Thus I had to split event_trigger and oidjoins tests into separate parallel groups. I'll post this as an independent patch then.\n\nThank you for catching it. Please, post this.\n\n------\nRegards,\nAlexander Korotkov\n\n\n", "msg_date": "Wed, 18 Oct 2023 13:34:49 +0300", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi Alexander,\n\n>> Thank you for catching it. Please, post this.\n\nJust for a more complete picture of the final state here.\nI have posted the described fix (for avoiding race condition in the tests)\nseparately:\nhttps://commitfest.postgresql.org/45/4616/\n\n--\n best regards,\n Mikhail A. Gribkov\n\ne-mail: youzhick@gmail.com\n\n\n\n>\n\nHi Alexander,>> Thank you for catching it.  Please, post this.Just for a more complete picture of the final state here.I have posted the described fix (for avoiding race condition in the tests) separately:https://commitfest.postgresql.org/45/4616/-- best regards,    Mikhail A. Gribkove-mail: youzhick@gmail.com", "msg_date": "Fri, 27 Oct 2023 09:27:13 +0300", "msg_from": "Mikhail Gribkov <youzhick@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Mikhail Gribkov <youzhick@gmail.com> writes:\n> Just for a more complete picture of the final state here.\n> I have posted the described fix (for avoiding race condition in the tests)\n> separately:\n> https://commitfest.postgresql.org/45/4616/\n\nIt turns out that the TAP test for this feature (006_login_trigger.pl)\nalso has a race condition:\n\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mamba&dt=2023-10-28%2003%3A33%3A28\n\nThe critical bit of the log is\n\nack Broken pipe: write( 14, 'SELECT 1;' ) at /usr/pkg/lib/perl5/vendor_perl/5.36.0/IPC/Run/IO.pm line 550.\n\nIt looks to me that what happened here is that the backend completed the\nauthentication handshake, and then the login trigger caused a FATAL exit,\nand after than the connected psql session tried to send \"SELECT 1\" on\nan already-closed pipe. That failed, causing IPC::Run to panic.\n\nmamba is a fairly slow machine and doubtless has timing a bit different\nfrom what this test was created on. But I doubt there is any way to make\nthis behavior perfectly stable across a range of machines, so I recommend\njust removing the test case involving a fatal exit.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 29 Oct 2023 11:16:01 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Sun, Oct 29, 2023 at 6:16 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Mikhail Gribkov <youzhick@gmail.com> writes:\n> > Just for a more complete picture of the final state here.\n> > I have posted the described fix (for avoiding race condition in the tests)\n> > separately:\n> > https://commitfest.postgresql.org/45/4616/\n>\n> It turns out that the TAP test for this feature (006_login_trigger.pl)\n> also has a race condition:\n>\n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mamba&dt=2023-10-28%2003%3A33%3A28\n>\n> The critical bit of the log is\n>\n> ack Broken pipe: write( 14, 'SELECT 1;' ) at /usr/pkg/lib/perl5/vendor_perl/5.36.0/IPC/Run/IO.pm line 550.\n>\n> It looks to me that what happened here is that the backend completed the\n> authentication handshake, and then the login trigger caused a FATAL exit,\n> and after than the connected psql session tried to send \"SELECT 1\" on\n> an already-closed pipe. That failed, causing IPC::Run to panic.\n>\n> mamba is a fairly slow machine and doubtless has timing a bit different\n> from what this test was created on. But I doubt there is any way to make\n> this behavior perfectly stable across a range of machines, so I recommend\n> just removing the test case involving a fatal exit.\n\nMakes sense. Are you good with the attached patch?\n\n------\nRegards,\nAlexander Korotkov", "msg_date": "Mon, 30 Oct 2023 01:09:56 +0300", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Alexander Korotkov <aekorotkov@gmail.com> writes:\n> On Sun, Oct 29, 2023 at 6:16 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> It looks to me that what happened here is that the backend completed the\n>> authentication handshake, and then the login trigger caused a FATAL exit,\n>> and after than the connected psql session tried to send \"SELECT 1\" on\n>> an already-closed pipe. That failed, causing IPC::Run to panic.\n\nLooking closer, what must have happened is that the psql session ended\nbefore IPC::Run could jam 'SELECT 1' into its stdin. I wonder if this\ncould be stabilized by doing 'psql -c \"SELECT 1\"' and not having to\nwrite anything to the child process stdin? But I'm not sure this test\ncase is valuable enough to put a great deal of work into.\n\n>> mamba is a fairly slow machine and doubtless has timing a bit different\n>> from what this test was created on. But I doubt there is any way to make\n>> this behavior perfectly stable across a range of machines, so I recommend\n>> just removing the test case involving a fatal exit.\n\n> Makes sense. Are you good with the attached patch?\n\nOK by me, though I note you misspelled \"mallory\" in the comment.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 29 Oct 2023 18:21:06 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hello Alexander,\n\nI've discovered one more instability in the event_trigger_login test.\nPlease look for example at case [1]:\nok 213       + event_trigger                           28946 ms\nnot ok 214   - event_trigger_login                      6430 ms\nok 215       - fast_default                            19349 ms\nok 216       - tablespace                              44789 ms\n1..216\n# 1 of 216 tests failed.\n\n--- /home/bf/bf-build/skink-master/HEAD/pgsql/src/test/regress/expected/event_trigger_login.out 2023-10-27 \n22:55:12.574139524 +0000\n+++ /home/bf/bf-build/skink-master/HEAD/pgsql.build/src/test/regress/results/event_trigger_login.out 2024-01-03 \n23:49:50.177461816 +0000\n@@ -40,6 +40,6 @@\n  SELECT dathasloginevt FROM pg_database WHERE datname= :'DBNAME';\n   dathasloginevt\n  ----------------\n- f\n+ t\n  (1 row)\n\n2024-01-03 23:49:40.378 UTC [2235175][client backend][3/5949:0] STATEMENT:  REINDEX INDEX CONCURRENTLY concur_reindex_ind;\n...\n2024-01-03 23:49:50.340 UTC [2260974][autovacuum worker][5/5439:18812] LOG:  automatic vacuum of table \n\"regression.pg_catalog.pg_statistic\": index scans: 1\n(operations logged around 23:49:50.177461816)\n\nI suspected that this failure was caused by autovacuum, and I've managed to\nreproduce it without Valgrind or slowing down a machine.\nWith /tmp/extra.config:\nlog_autovacuum_min_duration = 0\nautovacuum_naptime = 1\nautovacuum = on\n\nI run:\nfor ((i=1;i<10;i++)); do echo \"ITERATION $i\"; \\\nTEMP_CONFIG=/tmp/extra.config \\\nTESTS=$(printf 'event_trigger_login %.0s' `seq 1000`) \\\nmake -s check-tests || break; done\nand get failures on iterations 1, 2, 1...\nok 693       - event_trigger_login                        15 ms\nnot ok 694   - event_trigger_login                        15 ms\nok 695       - event_trigger_login                        21 ms\n\nAlso, I've observed an anomaly after dropping a login event trigger:\nCREATE FUNCTION on_login_proc() RETURNS event_trigger AS $$\nBEGIN RAISE NOTICE 'You are welcome!'; END; $$ LANGUAGE plpgsql;\nCREATE EVENT TRIGGER olt ON login EXECUTE PROCEDURE on_login_proc();\nSELECT dathasloginevt FROM pg_database WHERE datname= current_database();\n  dathasloginevt\n----------------\n  t\n(1 row)\n\nDROP EVENT TRIGGER olt;\nSELECT dathasloginevt FROM pg_database WHERE datname= current_database();\n  dathasloginevt\n----------------\n  t\n(1 row)\n\nAlthough after reconnection (\\c, as done in the event_trigger_login test),\nthis query returns 'f'.\n\n[1] https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=skink&dt=2024-01-03%2023%3A04%3A20\n[2] https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=skink&dt=2023-12-26%2019%3A33%3A02\n\nBest regards,\nAlexander\n\n\n", "msg_date": "Sat, 13 Jan 2024 19:00:01 +0300", "msg_from": "Alexander Lakhin <exclusion@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi, Alexander!\n\nOn Sat, Jan 13, 2024 at 6:00 PM Alexander Lakhin <exclusion@gmail.com> wrote:\n> I've discovered one more instability in the event_trigger_login test.\n> Please look for example at case [1]:\n> ok 213 + event_trigger 28946 ms\n> not ok 214 - event_trigger_login 6430 ms\n> ok 215 - fast_default 19349 ms\n> ok 216 - tablespace 44789 ms\n> 1..216\n> # 1 of 216 tests failed.\n\nThank you for reporting this.\n\nI'm going to take a closer look at this tomorrow. But I doubt I would\nfind a solution other than removing the flaky parts of the test.\n\n------\nRegards,\nAlexander Korotkov\n\n\n", "msg_date": "Mon, 15 Jan 2024 02:36:35 +0200", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 13 Jan 2024, at 17:00, Alexander Lakhin <exclusion@gmail.com> wrote:\n\n> DROP EVENT TRIGGER olt;\n> SELECT dathasloginevt FROM pg_database WHERE datname= current_database();\n> dathasloginevt\n> ----------------\n> t\n> (1 row)\n> \n> Although after reconnection (\\c, as done in the event_trigger_login test),\n> this query returns 'f'.\n\nThis is by design in the patch. The flag isn't changed on DROP, it is only\ncleared on logins iff there is no login event trigger. The description in the\ndocs is worded to indicate that it shouldn't be taken as truth for monitoring\npurposes:\n\n\t\"This flag is used internally by PostgreSQL and should not be manually\n\taltered or read for monitoring purposes.\"\n\n--\nDaniel Gustafsson\n\n\n\n", "msg_date": "Mon, 15 Jan 2024 10:05:26 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "> On 13 Jan 2024, at 17:00, Alexander Lakhin <exclusion@gmail.com> wrote:\n\n> I suspected that this failure was caused by autovacuum, and I've managed to\n> reproduce it without Valgrind or slowing down a machine.\n\nThis might be due to the fact that the cleanup codepath to remove the flag when\nthere is no login event trigger doesn't block on locking pg_database to avoid\nstalling connections. There are no guarantees when the flag is cleared, so a\ntest like this will always have potential to be flaky it seems.\n\n--\nDaniel Gustafsson\n\n\n\n", "msg_date": "Mon, 15 Jan 2024 10:29:25 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Mon, Jan 15, 2024 at 11:29 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n> > On 13 Jan 2024, at 17:00, Alexander Lakhin <exclusion@gmail.com> wrote:\n>\n> > I suspected that this failure was caused by autovacuum, and I've managed to\n> > reproduce it without Valgrind or slowing down a machine.\n>\n> This might be due to the fact that the cleanup codepath to remove the flag when\n> there is no login event trigger doesn't block on locking pg_database to avoid\n> stalling connections. There are no guarantees when the flag is cleared, so a\n> test like this will always have potential to be flaky it seems.\n\n+1\nThank you, Daniel. I think you described everything absolutely\ncorrectly. As I wrote upthread, it doesn't seem much could be done\nwith this, at least within a regression test. So, I just removed this\nquery from the test.\n\n------\nRegards,\nAlexander Korotkov\n\n\n", "msg_date": "Wed, 17 Jan 2024 23:25:02 +0200", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hello Alexander and Daniel,\n\nPlease look at the following query, which triggers an assertion failure on\nupdating the field dathasloginevt for an entry in pg_database:\nSELECT format('CREATE DATABASE db1 LOCALE_PROVIDER icu ICU_LOCALE en ENCODING utf8\nICU_RULES ''' || repeat(' ', 200000) || ''' TEMPLATE template0;')\n\\gexec\n\\c db1 -\n\nCREATE FUNCTION on_login_proc() RETURNS event_trigger AS $$\nBEGIN\n   RAISE NOTICE 'You are welcome!';\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE EVENT TRIGGER on_login_trigger ON login EXECUTE PROCEDURE on_login_proc();\nDROP EVENT TRIGGER on_login_trigger;\n\n\\c\n\n\\connect: connection to server on socket \"/tmp/.s.PGSQL.5432\" failed: server closed the connection unexpectedly\n\nThe stack trace of the assertion failure is:\n...\n#5  0x000055c8699b9b8d in ExceptionalCondition (\n     conditionName=conditionName@entry=0x55c869a1f7c0 \"HaveRegisteredOrActiveSnapshot()\",\n     fileName=fileName@entry=0x55c869a1f4c6 \"toast_internals.c\", lineNumber=lineNumber@entry=669) at assert.c:66\n#6  0x000055c86945df0a in init_toast_snapshot (...) at toast_internals.c:669\n#7  0x000055c86945dfbe in toast_delete_datum (...) at toast_internals.c:429\n#8  0x000055c8694fd1da in toast_tuple_cleanup (...) at toast_helper.c:309\n#9  0x000055c8694b55a1 in heap_toast_insert_or_update (...) at heaptoast.c:333\n#10 0x000055c8694a8c6c in heap_update (... at heapam.c:3604\n#11 0x000055c8694a96cb in simple_heap_update (...) at heapam.c:4062\n#12 0x000055c869555b7b in CatalogTupleUpdate (...) at indexing.c:322\n#13 0x000055c8695f0725 in EventTriggerOnLogin () at event_trigger.c:957\n...\n\nFunnily enough, when Tom Lane was wondering, whether pg_database's toast\ntable could pose a risk [1], I came to the conclusion that it's impossible,\nbut that was before the login triggers introduction...\n\n[1] https://www.postgresql.org/message-id/1284094.1695479962%40sss.pgh.pa.us\n\nBest regards,\nAlexander\n\n\n", "msg_date": "Tue, 23 Jan 2024 21:00:01 +0300", "msg_from": "Alexander Lakhin <exclusion@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Tue, Jan 23, 2024 at 8:00 PM Alexander Lakhin <exclusion@gmail.com> wrote:\n> Please look at the following query, which triggers an assertion failure on\n> updating the field dathasloginevt for an entry in pg_database:\n> SELECT format('CREATE DATABASE db1 LOCALE_PROVIDER icu ICU_LOCALE en ENCODING utf8\n> ICU_RULES ''' || repeat(' ', 200000) || ''' TEMPLATE template0;')\n> \\gexec\n> \\c db1 -\n>\n> CREATE FUNCTION on_login_proc() RETURNS event_trigger AS $$\n> BEGIN\n> RAISE NOTICE 'You are welcome!';\n> END;\n> $$ LANGUAGE plpgsql;\n>\n> CREATE EVENT TRIGGER on_login_trigger ON login EXECUTE PROCEDURE on_login_proc();\n> DROP EVENT TRIGGER on_login_trigger;\n>\n> \\c\n>\n> \\connect: connection to server on socket \"/tmp/.s.PGSQL.5432\" failed: server closed the connection unexpectedly\n>\n> The stack trace of the assertion failure is:\n> ...\n> #5 0x000055c8699b9b8d in ExceptionalCondition (\n> conditionName=conditionName@entry=0x55c869a1f7c0 \"HaveRegisteredOrActiveSnapshot()\",\n> fileName=fileName@entry=0x55c869a1f4c6 \"toast_internals.c\", lineNumber=lineNumber@entry=669) at assert.c:66\n> #6 0x000055c86945df0a in init_toast_snapshot (...) at toast_internals.c:669\n> #7 0x000055c86945dfbe in toast_delete_datum (...) at toast_internals.c:429\n> #8 0x000055c8694fd1da in toast_tuple_cleanup (...) at toast_helper.c:309\n> #9 0x000055c8694b55a1 in heap_toast_insert_or_update (...) at heaptoast.c:333\n> #10 0x000055c8694a8c6c in heap_update (... at heapam.c:3604\n> #11 0x000055c8694a96cb in simple_heap_update (...) at heapam.c:4062\n> #12 0x000055c869555b7b in CatalogTupleUpdate (...) at indexing.c:322\n> #13 0x000055c8695f0725 in EventTriggerOnLogin () at event_trigger.c:957\n> ...\n>\n> Funnily enough, when Tom Lane was wondering, whether pg_database's toast\n> table could pose a risk [1], I came to the conclusion that it's impossible,\n> but that was before the login triggers introduction...\n>\n> [1] https://www.postgresql.org/message-id/1284094.1695479962%40sss.pgh.pa.us\n\nThank you for reporting. I'm looking into this...\nI wonder if there is a way to avoid toast update given that we don't\ntouch the toasted field here.\n\n------\nRegards,\nAlexander Korotkov\n\n\n", "msg_date": "Tue, 23 Jan 2024 23:52:24 +0200", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Tue, Jan 23, 2024 at 11:52 PM Alexander Korotkov\n<aekorotkov@gmail.com> wrote:\n> On Tue, Jan 23, 2024 at 8:00 PM Alexander Lakhin <exclusion@gmail.com> wrote:\n> > Please look at the following query, which triggers an assertion failure on\n> > updating the field dathasloginevt for an entry in pg_database:\n> > SELECT format('CREATE DATABASE db1 LOCALE_PROVIDER icu ICU_LOCALE en ENCODING utf8\n> > ICU_RULES ''' || repeat(' ', 200000) || ''' TEMPLATE template0;')\n> > \\gexec\n> > \\c db1 -\n> >\n> > CREATE FUNCTION on_login_proc() RETURNS event_trigger AS $$\n> > BEGIN\n> > RAISE NOTICE 'You are welcome!';\n> > END;\n> > $$ LANGUAGE plpgsql;\n> >\n> > CREATE EVENT TRIGGER on_login_trigger ON login EXECUTE PROCEDURE on_login_proc();\n> > DROP EVENT TRIGGER on_login_trigger;\n> >\n> > \\c\n> >\n> > \\connect: connection to server on socket \"/tmp/.s.PGSQL.5432\" failed: server closed the connection unexpectedly\n> >\n> > The stack trace of the assertion failure is:\n> > ...\n> > #5 0x000055c8699b9b8d in ExceptionalCondition (\n> > conditionName=conditionName@entry=0x55c869a1f7c0 \"HaveRegisteredOrActiveSnapshot()\",\n> > fileName=fileName@entry=0x55c869a1f4c6 \"toast_internals.c\", lineNumber=lineNumber@entry=669) at assert.c:66\n> > #6 0x000055c86945df0a in init_toast_snapshot (...) at toast_internals.c:669\n> > #7 0x000055c86945dfbe in toast_delete_datum (...) at toast_internals.c:429\n> > #8 0x000055c8694fd1da in toast_tuple_cleanup (...) at toast_helper.c:309\n> > #9 0x000055c8694b55a1 in heap_toast_insert_or_update (...) at heaptoast.c:333\n> > #10 0x000055c8694a8c6c in heap_update (... at heapam.c:3604\n> > #11 0x000055c8694a96cb in simple_heap_update (...) at heapam.c:4062\n> > #12 0x000055c869555b7b in CatalogTupleUpdate (...) at indexing.c:322\n> > #13 0x000055c8695f0725 in EventTriggerOnLogin () at event_trigger.c:957\n> > ...\n> >\n> > Funnily enough, when Tom Lane was wondering, whether pg_database's toast\n> > table could pose a risk [1], I came to the conclusion that it's impossible,\n> > but that was before the login triggers introduction...\n> >\n> > [1] https://www.postgresql.org/message-id/1284094.1695479962%40sss.pgh.pa.us\n>\n> Thank you for reporting. I'm looking into this...\n> I wonder if there is a way to avoid toast update given that we don't\n> touch the toasted field here.\n\nUsage of heap_inplace_update() seems appropriate for me here. It\navoids trouble with both TOAST and row-level locks. Alexander, could\nyou please recheck this fixes the problem.\n\n------\nRegards,\nAlexander Korotkov", "msg_date": "Mon, 5 Feb 2024 01:51:34 +0200", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hello Alexander,\n\n05.02.2024 02:51, Alexander Korotkov wrote:\n\n> Usage of heap_inplace_update() seems appropriate for me here. It\n> avoids trouble with both TOAST and row-level locks. Alexander, could\n> you please recheck this fixes the problem.\n\nI've re-tested the last problematic scenario and can confirm that the fix\nworks for it (though it still doesn't prevent the autovacuum issue (with\n4b885d01 reverted)), but using heap_inplace_update() was considered risky\nin a recent discussion:\nhttps://www.postgresql.org/message-id/1596629.1698435146%40sss.pgh.pa.us\nSo maybe it's worth to postpone such a fix till that discussion is\nfinished or to look for another approach...\n\nBest regards,\nAlexander\n\n\n", "msg_date": "Mon, 5 Feb 2024 20:00:01 +0300", "msg_from": "Alexander Lakhin <exclusion@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "Hi, Alexander!\n\nOn Mon, Feb 5, 2024 at 7:00 PM Alexander Lakhin <exclusion@gmail.com> wrote:\n> 05.02.2024 02:51, Alexander Korotkov wrote:\n>\n> > Usage of heap_inplace_update() seems appropriate for me here. It\n> > avoids trouble with both TOAST and row-level locks. Alexander, could\n> > you please recheck this fixes the problem.\n>\n> I've re-tested the last problematic scenario and can confirm that the fix\n> works for it (though it still doesn't prevent the autovacuum issue (with\n> 4b885d01 reverted)), but using heap_inplace_update() was considered risky\n> in a recent discussion:\n> https://www.postgresql.org/message-id/1596629.1698435146%40sss.pgh.pa.us\n> So maybe it's worth to postpone such a fix till that discussion is\n> finished or to look for another approach...\n\nThank you for pointing this out. I don't think there is a particular\nproblem with this use case for the following reasons.\n1) Race conditions over pg_database.dathasloginevt are protected with lock tag.\n2) Unsetting pg_database.dathasloginevt of old tuple version shouldn't\ncause a problem. The next tuple version will be updated by further\nconnections.\nHowever, I agree that it's better to wait for the discussion you've\npointed out before introducing another use case of\nheap_inplace_update().\n\n------\nRegards,\nAlexander Korotkov\n\n\n", "msg_date": "Mon, 5 Feb 2024 22:28:24 +0200", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" }, { "msg_contents": "On Mon, Oct 16, 2023 at 6:36 AM Alexander Korotkov <aekorotkov@gmail.com> wrote:\n>\n> > On Mon, Oct 16, 2023 at 02:47:03AM +0300, Alexander Korotkov wrote:\n> > > The attached revision fixes test failures spotted by\n> > > commitfest.cputube.org. Also, perl scripts passed perltidy.\n>\n> You are very fast and sharp eye!\n> Thank you for fixing the indentation. I just pushed fixes for the rest.\n\nI noticed some typos related to this feature.\n\nWhile on this, the event trigger example for C programming language\nshown in the docs doesn't compile as-is. fmgr.h is needed.\n\nPlease see the attached patch.\n\n[1]\n2024-02-06 05:31:24.453 UTC [1401414] LOG: tag LOGIN, event login\n\n#include \"postgres.h\"\n\n#include \"commands/event_trigger.h\"\n#include \"fmgr.h\"\n\nPG_MODULE_MAGIC;\n\nPG_FUNCTION_INFO_V1(onlogin);\n\nDatum\nonlogin(PG_FUNCTION_ARGS)\n{\n EventTriggerData *trigdata;\n\n if (!CALLED_AS_EVENT_TRIGGER(fcinfo)) /* internal error */\n elog(ERROR, \"not fired by event trigger manager\");\n\n trigdata = (EventTriggerData *) fcinfo->context;\n\n elog(LOG, \"tag %s, event %s\", GetCommandTagName(trigdata->tag),\ntrigdata->event);\n\n PG_RETURN_NULL();\n}\n\ngcc -shared -fPIC -I /home/ubuntu/postgres/pg17/include/server -o\nlogin_trigger.so login_trigger.c\n\nLOAD '/home/ubuntu/postgres/login_trigger.so';\n\nCREATE FUNCTION onlogin() RETURNS event_trigger\n AS '/home/ubuntu/postgres/login_trigger' LANGUAGE C;\n\nCREATE EVENT TRIGGER onlogin ON login\n EXECUTE FUNCTION onlogin();\n\n-- \nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com", "msg_date": "Tue, 6 Feb 2024 11:27:45 +0530", "msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>", "msg_from_op": false, "msg_subject": "Re: On login trigger: take three" } ]
[ { "msg_contents": "A pretty minor issue: when reporting that WAL appears invalid because\ncontrecord length doesn't match, we may as well print to the server log\nthe value that we're expecting. Patch attached.\n\n-- \n�lvaro Herrera http://www.flickr.com/photos/alvherre/", "msg_date": "Thu, 3 Sep 2020 17:21:52 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "report expected contrecord size" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> A pretty minor issue: when reporting that WAL appears invalid because\n> contrecord length doesn't match, we may as well print to the server log\n> the value that we're expecting. Patch attached.\n\nITYW\n\n+ (long long) (total_len - gotlen),\n\njust to be sure about what's getting casted to what. Otherwise +1.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 03 Sep 2020 17:31:31 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: report expected contrecord size" }, { "msg_contents": "On 2020-Sep-03, Tom Lane wrote:\n\n> Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> > A pretty minor issue: when reporting that WAL appears invalid because\n> > contrecord length doesn't match, we may as well print to the server log\n> > the value that we're expecting. Patch attached.\n> \n> ITYW\n> \n> + (long long) (total_len - gotlen),\n> \n> just to be sure about what's getting casted to what.\n\nWell, the intention there is to cast the first operand (which is uint32)\nso that it turns into signed 64-bits; the subtraction then occurs in 64\nbit arithmetic normally. If I let the subtraction occur in 32-bit width\nunsigned, the result might overflow 32 bits. I'm thinking in\n1 - UINT32_MAX or some such.\n\nMaybe to make that more explicit, it should be\n\n+ ((long long) total_len) - gotlen,\n\n(If I understand the precedence correctly, it's the same thing I wrote).\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 3 Sep 2020 18:00:34 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: report expected contrecord size" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> Well, the intention there is to cast the first operand (which is uint32)\n> so that it turns into signed 64-bits; the subtraction then occurs in 64\n> bit arithmetic normally. If I let the subtraction occur in 32-bit width\n> unsigned, the result might overflow 32 bits.\n\nUh ... is it really possible for gotlen to be more than total_len?\n(I've not looked at the surrounding code here, but that seems weird.)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 03 Sep 2020 18:17:30 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: report expected contrecord size" }, { "msg_contents": "On 2020-Sep-03, Tom Lane wrote:\n\n> Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> > Well, the intention there is to cast the first operand (which is uint32)\n> > so that it turns into signed 64-bits; the subtraction then occurs in 64\n> > bit arithmetic normally. If I let the subtraction occur in 32-bit width\n> > unsigned, the result might overflow 32 bits.\n> \n> Uh ... is it really possible for gotlen to be more than total_len?\n> (I've not looked at the surrounding code here, but that seems weird.)\n\nWell, as I understand, total_len comes from one page, and gotlen comes\nfrom the continuation record(s) in the next page(s) of WAL. So if\nthings are messed up, it could happen. (This *is* the code that\nvalidates the record, so it can't make too many assumptions.)\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 3 Sep 2020 18:33:08 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: report expected contrecord size" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> On 2020-Sep-03, Tom Lane wrote:\n>> Uh ... is it really possible for gotlen to be more than total_len?\n>> (I've not looked at the surrounding code here, but that seems weird.)\n\n> Well, as I understand, total_len comes from one page, and gotlen comes\n> from the continuation record(s) in the next page(s) of WAL. So if\n> things are messed up, it could happen. (This *is* the code that\n> validates the record, so it can't make too many assumptions.)\n\nGot it. No further objections.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 03 Sep 2020 18:42:02 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: report expected contrecord size" }, { "msg_contents": "On 2020-Sep-03, Tom Lane wrote:\n\n> Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> > On 2020-Sep-03, Tom Lane wrote:\n> >> Uh ... is it really possible for gotlen to be more than total_len?\n> >> (I've not looked at the surrounding code here, but that seems weird.)\n> \n> > Well, as I understand, total_len comes from one page, and gotlen comes\n> > from the continuation record(s) in the next page(s) of WAL. So if\n> > things are messed up, it could happen. (This *is* the code that\n> > validates the record, so it can't make too many assumptions.)\n> \n> Got it. No further objections.\n\nMany thanks for looking! Pushed now.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 4 Sep 2020 15:00:26 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: report expected contrecord size" } ]
[ { "msg_contents": "Hi all,\n\nconchuela has just reported the following error:\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=conchuela&dt=2020-09-03%2023%3A00%3A36\n\n-- Drop access method cascade\n DROP ACCESS METHOD gist2 CASCADE;\n NOTICE: drop cascades to index grect2ind2\n+ERROR: deadlock detected\n+DETAIL: Process 609175 waits for AccessExclusiveLock on relation 17347 of database 16384; blocked by process 609183.\n+Process 609183 waits for RowExclusiveLock on relation 20095 of database 16384; blocked by process 609175.\n+HINT: See server log for query details.\n\nLooking at the logs, 609183 is running an autovacuum analyze:\n2020-09-04 01:04:52.895 CEST [609183:6] LOG: automatic analyze of\ntable \"regression.public.tenk2\" system usage: CPU: user: 0.03 s,\nsystem: 0.00 s, elapsed: 0.59 s\n\nI have not looked at that stuff much yet.\n\nThanks,\n--\nMichael", "msg_date": "Fri, 4 Sep 2020 11:03:45 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Concurrent failure in create_am with buildfarm member conchuela" }, { "msg_contents": "Hello,\n\nOn 2020-Sep-04, Michael Paquier wrote:\n\n> conchuela has just reported the following error:\n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=conchuela&dt=2020-09-03%2023%3A00%3A36\n\nFixed in d54f99e4154.\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, 4 Sep 2020 15:38:32 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Concurrent failure in create_am with buildfarm member conchuela" }, { "msg_contents": "On Fri, Sep 04, 2020 at 03:38:32PM -0400, Alvaro Herrera wrote:\n> Fixed in d54f99e4154.\n\nYes, thanks. I bumped into the other thread this morning:\nhttps://www.postgresql.org/message-id/839004.1599185607@sss.pgh.pa.us\nThe fix makes sense.\n--\nMichael", "msg_date": "Sat, 5 Sep 2020 10:37:38 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Concurrent failure in create_am with buildfarm member conchuela" } ]
[ { "msg_contents": "conchuela just showed an unusual failure:\n\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=conchuela&dt=2020-09-03%2023%3A00%3A36\n\nThe core of it is a deadlock failure in create_am.sql; there's then\nsome follow-on noise from not having successfully dropped the test AM.\nThe deadlock looks like:\n\n2020-09-04 01:05:06.904 CEST [609175:34] pg_regress/create_am LOG: process 609175 detected deadlock while waiting for AccessExclusiveLock on relation 17347 of database 16384 after 4616.873 ms\n2020-09-04 01:05:06.904 CEST [609175:35] pg_regress/create_am DETAIL: Process holding the lock: 609183. Wait queue: .\n2020-09-04 01:05:06.904 CEST [609175:36] pg_regress/create_am STATEMENT: DROP ACCESS METHOD gist2 CASCADE;\n2020-09-04 01:05:06.904 CEST [609175:37] pg_regress/create_am ERROR: deadlock detected\n2020-09-04 01:05:06.904 CEST [609175:38] pg_regress/create_am DETAIL: Process 609175 waits for AccessExclusiveLock on relation 17347 of database 16384; blocked by process 609183.\n\tProcess 609183 waits for RowExclusiveLock on relation 20095 of database 16384; blocked by process 609175.\n\tProcess 609175: DROP ACCESS METHOD gist2 CASCADE;\n\tProcess 609183: autovacuum: VACUUM ANALYZE public.fast_emp4000\n2020-09-04 01:05:06.904 CEST [609175:39] pg_regress/create_am HINT: See server log for query details.\n2020-09-04 01:05:06.904 CEST [609175:40] pg_regress/create_am STATEMENT: DROP ACCESS METHOD gist2 CASCADE;\n2020-09-04 01:05:06.904 CEST [609183:11] LOG: process 609183 acquired RowExclusiveLock on relation 20095 of database 16384 after 13377.776 ms\n2020-09-04 01:04:52.895 CEST [609183:6] LOG: automatic analyze of table \"regression.public.tenk2\" system usage: CPU: user: 0.03 s, system: 0.00 s, elapsed: 0.59 s\n\nSo it's not hard to understand the problem: DROP of an index AM, cascading\nto an index, will need to acquire lock on the index and then lock on the\nindex's table. Any other operation on the table, like say autovacuum,\nis going to acquire locks in the other direction.\n\nThis is pretty rare, but not unheard of:\n\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=grison&dt=2020-03-24%2022%3A00%3A23\n\n(There might be more such failures, but I only looked back six months,\nand these two are all I found in that window.)\n\nI'm inclined to think that the best fix is to put\n\nbegin;\nlock table tenk2;\n...\ncommit;\n\naround the DROP CASCADE. We could alternatively disable autovacuum on\ntenk2, but that could have undesirable side-effects.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 03 Sep 2020 22:13:27 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Rare deadlock failure in create_am test" }, { "msg_contents": "On Fri, Sep 4, 2020 at 2:13 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> (There might be more such failures, but I only looked back six months,\n> and these two are all I found in that window.)\n\nRight:\n\n https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=conchuela&dt=2020-09-03%2023:00:36\n | HEAD | DragonflyBSD\n https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=lapwing&dt=2020-04-08%2004:38:34\n | HEAD | Debian\n https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=tern&dt=2020-03-30%2013:54:05\n | HEAD | AIX\n https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=grison&dt=2020-03-24%2022:00:23\n | HEAD | Raspbian\n https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=culicidae&dt=2020-03-03%2016:10:06\n | HEAD | Debian\n https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=longfin&dt=2019-12-11%2023:59:06\n | HEAD | macOS\n https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=longfin&dt=2019-12-11%2022:09:07\n | HEAD | macOS\n https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=fairywren&dt=2019-12-10%2003:46:12\n | REL9_6_STABLE |\n https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mandrill&dt=2019-07-10%2023:19:12\n | REL9_6_STABLE | AIX\n https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=dangomushi&dt=2018-06-23%2018:00:15\n| HEAD | Arch\n\n> I'm inclined to think that the best fix is to put\n>\n> begin;\n> lock table tenk2;\n> ...\n> commit;\n\nMakes sense, except s/tenk2/fast_emp4000/, no?\n\n\n", "msg_date": "Fri, 4 Sep 2020 22:02:08 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Rare deadlock failure in create_am test" }, { "msg_contents": "Thomas Munro <thomas.munro@gmail.com> writes:\n> On Fri, Sep 4, 2020 at 2:13 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> I'm inclined to think that the best fix is to put\n>> \n>> begin;\n>> lock table tenk2;\n>> ...\n>> commit;\n\n> Makes sense, except s/tenk2/fast_emp4000/, no?\n\nSorry, thinko ...\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 04 Sep 2020 09:58:35 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Rare deadlock failure in create_am test" }, { "msg_contents": "On 2020-Sep-03, Tom Lane wrote:\n\n> So it's not hard to understand the problem: DROP of an index AM, cascading\n> to an index, will need to acquire lock on the index and then lock on the\n> index's table. Any other operation on the table, like say autovacuum,\n> is going to acquire locks in the other direction.\n\nOh, of course.\n\n> I'm inclined to think that the best fix is to put\n> \n> begin;\n> lock table [fast_emp4000];\n> ...\n> commit;\n> \n> around the DROP CASCADE.\n\nYeah, sounds good.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 4 Sep 2020 10:20:33 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Rare deadlock failure in create_am test" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> On 2020-Sep-03, Tom Lane wrote:\n>> I'm inclined to think that the best fix is to put\n>> \n>> begin;\n>> lock table [fast_emp4000];\n>> ...\n>> commit;\n>> \n>> around the DROP CASCADE.\n\n> Yeah, sounds good.\n\nDone.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 04 Sep 2020 12:41:23 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Rare deadlock failure in create_am test" }, { "msg_contents": "On 2020-09-04 12:41:23 -0400, Tom Lane wrote:\n> Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> > On 2020-Sep-03, Tom Lane wrote:\n> >> I'm inclined to think that the best fix is to put\n> >> \n> >> begin;\n> >> lock table [fast_emp4000];\n> >> ...\n> >> commit;\n> >> \n> >> around the DROP CASCADE.\n> \n> > Yeah, sounds good.\n> \n> Done.\n\nThanks!\n\n\n", "msg_date": "Tue, 8 Sep 2020 10:56:26 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Rare deadlock failure in create_am test" } ]
[ { "msg_contents": "\nGreetins hackers,\n\nI have mixed feelings if this welcome contribution as the potential gain is relatively small in my tests, but still I would like to point out that HASH_FFACTOR functionality from dynahash.c could be removed or optimized (default fill factor is always 1, there's not a single place that uses custom custom fill factor other than DEF_FFACTOR=1 inside PostgreSQL repository). Because the functionality is present there seems to be division for every buffer access [BufTableLookup()] / or every smgropen() call (everything call to hash_search() is affected, provided it's not ShmemInitHash/HASH_PARTITION). This division is especially visible via perf on single process StartupXLOG WAL recovery process on standby in heavy duty 100% CPU conditions , as the top1 is inside hash_search:\n   0x0000000000888751 <+449>:   idiv   r8\n   0x0000000000888754 <+452>:   cmp    rax,QWORD PTR [r15+0x338] <<-- in perf annotate shows as 30-40%, even on default -O2, probably CPU pipelining for idiv above\n\nI've made a PoC test to skip that division assuming ffactor would be gone:\n if (!IS_PARTITIONED(hctl) && !hashp->frozen &&\n-                       hctl->freeList[0].nentries / (long) (hctl->max_bucket + 1) >= hctl->ffactor &&\n+                       hctl->freeList[0].nentries >= (long) (hctl->max_bucket + 1) &&\n\nFor a stream of WAL 3.7GB I'm getting consistent improvement of ~4%, (yes I know it's small, that's why I'm having mixed feelings):\ngcc -O3: 104->100s\ngcc -O2: 108->104s\npgbench -S -c 16 -j 4 -T 30 -M prepared: stays more or less the same (-s 100), so no positive impact there\n\nAfter removing HASH_FFACTOR PostgreSQL still compiles...  Would removing it break some external API/extensions ? I saw several optimization for the \"idiv\" where it could be optimized e.g. see https://github.com/ridiculousfish/libdivide Or maybe there is some other idea to expose bottlenecks of BufTableLookup() ? I also saw codepath PinBuffer()->GetPrivateRefCountEntry() -> dynahash that could be called pretty often I have no idea what kind of pgbench stresstest could be used to demonstrate the gain (or lack of it).\n\n-Jakub Wartak.\n\n", "msg_date": "Fri, 4 Sep 2020 07:01:41 +0000", "msg_from": "Jakub Wartak <Jakub.Wartak@tomtom.com>", "msg_from_op": true, "msg_subject": "Division in dynahash.c due to HASH_FFACTOR" }, { "msg_contents": "On Fri, Sep 04, 2020 at 07:01:41AM +0000, Jakub Wartak wrote:\n>\n>Greetins hackers,\n>\n>I have mixed feelings if this welcome contribution as the potential\n>gain is relatively small in my tests, but still I would like to point\n>out that HASH_FFACTOR functionality from dynahash.c could be removed or\n>optimized (default fill factor is always 1, there's not a single place\n>that uses custom custom fill factor other than DEF_FFACTOR=1 inside\n>PostgreSQL repository). Because the functionality is present there\n>seems to be division for every buffer access [BufTableLookup()] / or\n>every smgropen() call (everything call to hash_search() is affected,\n>provided it's not ShmemInitHash/HASH_PARTITION). This division is\n>especially visible via perf on single process StartupXLOG WAL recovery\n>process on standby in heavy duty 100% CPU conditions , as the top1 is\n>inside hash_search:\n>\n>� �0x0000000000888751 <+449>: � idiv � r8\n>� �0x0000000000888754 <+452>: � cmp � �rax,QWORD PTR [r15+0x338] <<-- in perf annotate shows as 30-40%, even on default -O2, probably CPU pipelining for idiv above\n>\n>I've made a PoC test to skip that division assuming ffactor would be gone:\n> if (!IS_PARTITIONED(hctl) && !hashp->frozen &&\n>- � � � � � � � � � � � hctl->freeList[0].nentries / (long) (hctl->max_bucket + 1) >= hctl->ffactor &&\n>+ � � � � � � � � � � � hctl->freeList[0].nentries >= (long) (hctl->max_bucket + 1) &&\n>\n>For a stream of WAL 3.7GB I'm getting consistent improvement of ~4%, (yes I know it's small, that's why I'm having mixed feelings):\n>gcc -O3: 104->100s\n>gcc -O2: 108->104s\n>pgbench -S -c 16 -j 4 -T 30 -M prepared: stays more or less the same (-s 100), so no positive impact there\n>\n\nHmm, so it's the division that makes the difference? In that case,\nwouldn't it make sense to just compute a threshold every time the hash\ntable is resized, and then do just the comparison. That is, compute\n\n nentries_threshold = (long) (hctl->max_bucket + 1) * hctl->ffactor;\n\nand then do just\n\n hctl->freeList[0].nentries >= nentries_threshold\n\nOf course, this assumes the threshold is calculated only rarely, maybe\nthat's not the case.\n\nAlso, what if you lower the fill factor, e.g. to 0.8? Does that improve\nperformance or not? I can't find any discussion about this in the\narchives, but the dynamic hashing paper [1] seems to suggest it does\nmake a difference (see the tables at the end, but I haven't re-read the\npaper recently so maybe it's irrelevant). Anyway, it'd be foolish to\nremove the ffactor parameter to save on division only to lose the\nability to lower the factor and save more than that ...\n\n\nAs for the 4% - it's not much, but it's also not negligible. I'm sure\nwe've done micro-optimizations for smaller gains. The big question is\nwhether this is statistically significant, or whether it's just due to\nrandom effects. It could easily be caused by changes in layout of the\nbinary, for example - that can happen quite easily. See [2] and [3].\n\nThe talk actually mentions a tool meant to eliminate this bias by\nrandomization, but I've never tried using it on PostgreSQL so I'm not\nsure how compatible it is :-(\n\n\n[1] https://www.csd.uoc.gr/~hy460/pdf/Dynamic%20Hash%20Tables.pdf\n[2] https://www.cis.upenn.edu/~cis501/previous/fall2016/papers/producing-wrong-data.pdf\n[3] https://www.youtube.com/watch?v=r-TLSBdHe1A\n\n>After removing HASH_FFACTOR PostgreSQL still compiles... �Would\n>removing it break some external API/extensions ? I saw several\n>optimization for the \"idiv\" where it could be optimized e.g. see\n>https://github.com/ridiculousfish/libdivide Or maybe there is some\n>other idea to expose bottlenecks of BufTableLookup() ? I also saw\n>codepath PinBuffer()->GetPrivateRefCountEntry() -> dynahash that could\n>be called pretty often I have no idea what kind of pgbench stresstest\n>could be used to demonstrate the gain (or lack of it).\n>\n>-Jakub Wartak.\n>\n\nI don't think whit would break a lot of stuff, but I'm kinda dubious\nit's a measurable improvement for common workloads ...\n\n\nregards\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 4 Sep 2020 14:04:36 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Division in dynahash.c due to HASH_FFACTOR" }, { "msg_contents": "On 2020-Sep-04, Jakub Wartak wrote:\n\n> After removing HASH_FFACTOR PostgreSQL still compiles... �Would\n> removing it break some external API/extensions ?\n\nFWIW, HASH_FFACTOR has *never* been used in Postgres core code.\n\nhttps://postgr.es/m/20160418180711.55ac82c0@fujitsu already reported\nthat this flag was unused a few years ago. And a search through\ncodesearch.debian.net shows that no software packaged by Debian uses\nthat flag either.\n\n*If* any third-party extension is using HASH_FFACTOR, it can easily be\nunbroken by removing the flag or #defining it to zero; the removal would\nonly be a problem if anyone showed that there is a performance loss by\nusing the default fillfactor for some dynahash table instead of their\ncustom value.\n\nI think if we know that there's a 4% performance increase by removing\nthe division that comes with an ability to use a custom fillfactor that\nnobody uses or has ever used, it makes sense to remove that ability.\n\n... however, if we're really tense about improving some hash table's\nperformance, it might be worth trying to use simplehash.h instead of\ndynahash.c for it.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 4 Sep 2020 10:34:39 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Division in dynahash.c due to HASH_FFACTOR" }, { "msg_contents": "On Sat, Sep 5, 2020 at 2:34 AM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n> On 2020-Sep-04, Jakub Wartak wrote:\n> > After removing HASH_FFACTOR PostgreSQL still compiles... Would\n> > removing it break some external API/extensions ?\n>\n> FWIW, HASH_FFACTOR has *never* been used in Postgres core code.\n>\n> https://postgr.es/m/20160418180711.55ac82c0@fujitsu already reported\n> that this flag was unused a few years ago. And a search through\n> codesearch.debian.net shows that no software packaged by Debian uses\n> that flag either.\n>\n> *If* any third-party extension is using HASH_FFACTOR, it can easily be\n> unbroken by removing the flag or #defining it to zero; the removal would\n> only be a problem if anyone showed that there is a performance loss by\n> using the default fillfactor for some dynahash table instead of their\n> custom value.\n>\n> I think if we know that there's a 4% performance increase by removing\n> the division that comes with an ability to use a custom fillfactor that\n> nobody uses or has ever used, it makes sense to remove that ability.\n\nI think Tomas is right, and the correct fix for this would be to\ncompute it up front every time the hash table size changes, but since\napparently no one ever used it, +1 for just removing it and leaving it\nhard-coded.\n\nFor what it's worth, for dshash.c I just hard coded it to double the\nhash table size whenever the number of elements in a partition\nexceeded 75%. Popular hash tables in standard libraries seem to use\neither .75 or 1.0 as a default or only setting. There's probably room\nfor discussion about numbers in those ranges, but I think the concept\nof customisable load factors with a range much wider than that may be\nmore relevant for disk-based hash tables (like our hash indexes),\nwhich have very different economics. I think the name HASH_FFACTOR\nmay be a clue that this was possibly interference from disk-based hash\ntables from the same Berkeley people: rather than \"load factor\", the\nmore usual term (?) for nentries/nbuckets in memory-based hash tables\nas a way to model number of expected collisions, they called it \"fill\nfactor\", which I guess is because in disk-based designs your actually\nwant a certain rate of collisions, because you're working not with\nelements in an array and wanting to avoid collisions while not wasting\nspace, but rather with fixed sized buckets that you want to fill up,\nbut not overflow. </archeological-speculation-mode>\n\n> ... however, if we're really tense about improving some hash table's\n> performance, it might be worth trying to use simplehash.h instead of\n> dynahash.c for it.\n\nSure, but removing the dynahash IDIV also seems like a slam dunk\nremoval of a useless expensive feature.\n\n\n", "msg_date": "Tue, 8 Sep 2020 12:55:32 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Division in dynahash.c due to HASH_FFACTOR" }, { "msg_contents": "Hi Thomas, Tomas :), Alvaro, hackers,\n\n>> > After removing HASH_FFACTOR PostgreSQL still compiles... Would\n>> > removing it break some external API/extensions ?\n>>\n>> FWIW, HASH_FFACTOR has *never* been used in Postgres core code.\n[..]\n>> I think if we know that there's a 4% performance increase by removing\n>> the division that comes with an ability to use a custom fillfactor that\n>> nobody uses or has ever used, it makes sense to remove that ability.\n\nThomas wrote:\n>I think Tomas is right, and the correct fix for this would be to\n>compute it up front every time the hash table size changes, but since\n>apparently no one ever used it, +1 for just removing it and leaving it\n>hard-coded.\n[..]\n>For what it's worth, for dshash.c I just hard coded it to double the\n>hash table size whenever the number of elements in a partition\n>exceeded 75%. Popular hash tables in standard libraries seem to use\n>either .75 or 1.0 as a default or only setting. There's probably room\n>for discussion about numbers in those ranges, (..)\n\nTomas also asked the same \"what if you lower the fill factor, e.g. to 0.8? Does that improve performance or not?\" and got some interesting links for avoiding bias. I couldn't find any other simple way to benchmark a real impact of it other than checking DB crash-recovery (if anyone has some artificial workload generator with PinBuffer->hash_search() please let me know).\n\nSo I've been testing it using WAL crash-recovery using Thomas's approach [1]: always the same workload to reply, always on the same machine, same env: same 13GB WAL to recover, 8GB db, 24GB shared buffers on top of 128GB RAM, NVMe with fsync off to put dynahash as primary bottleneck (BufTableLookup()+smgropen()), append-only workload, gcc -O3: Results are <1st time is the WAL recovery timing, 2nd time is checkpoint before opening DB>. There were four measurements per each scenario, first one is cut off to avoid noise:\n\n1. DEF_FFACTOR=1 idiv on\n103.971, 3.719\n103.937, 3.683\n104.934, 3.691\n\n2. DEF_FFACTOR=1 idiv off\n100.565, 3.71\n101.595, 3.807\n100.794, 3.691\n\n3. DEF_FFACTOR=1.2 idiv on // some proof that nobody uses it\n1599552729.041 postmaster 94510 FATAL: failed to initialize hash table \"SERIALIZABLEXID hash\"\n\n4. DEF_FFACTOR=0.8 idiv on // another proof ? The reason for below is that ffactor is long and as such cannot handle floats, if it would be float....\n\nProgram terminated with signal 8, Arithmetic exception.\n#0 0x00000000009a4119 in init_htab (nelem=4, hashp=0x17cd238) at dynahash.c:677\n677 nbuckets = next_pow2_int((nelem - 1) / hctl->ffactor + 1);\nMissing separate debuginfos, use: debuginfo-install glibc-2.17-292.180.amzn1.x86_64\n\n#0 0x00000000009a4119 in init_htab (nelem=4, hashp=0x17cd238) at dynahash.c:677\n#1 hash_create (tabname=tabname@entry=0xb77f9a \"Timezones\", nelem=nelem@entry=4, info=info@entry=0x7ffd3055cf30, flags=flags@entry=16) at dynahash.c:529\n#2 0x00000000009ecddf in init_timezone_hashtable () at pgtz.c:211\n#3 pg_tzset (name=name@entry=0xb49fd5 \"GMT\") at pgtz.c:248\n#4 0x00000000009ecfee in pg_timezone_initialize () at pgtz.c:372\n\n5. DEF_FFACTOR=1 idiv on // just in case reproducer to validate measurement #1\n104.333, 3.804\n104.313, 3.772\n103.951, 3.687\n\n6. DEF_FFACTOR=2 idiv on\n105.406, 3.783\n105.33, 3.721\n105.403, 3.777\n\n7. DEF_FFACTOR=4 idiv on\n105.803, 3.722\n105.73, 3.728\n106.104, 3.756\n\nSome notes:\n- SMgrRelationHash is initialized from start at 400, while DB here is small 8GB and has only couple of tables -> no expansion needed in above test.\n- local backend private overflow hash table for buffers: PrivateRefCountHash is initialized at 100 and maybe it grows during\n- googling for DEF_FFACTOR I've found only 1 entry with value of <> 1 from 1993 (see this [2] , what's interesting is the same DEF_SEGSIZE value after all those years)\n\nAlvaro wrote:\n>> ... however, if we're really tense about improving some hash table's\n>> performance, it might be worth trying to use simplehash.h instead of\n>> dynahash.c for it.\n\nThomas wrote:\n> Sure, but removing the dynahash IDIV also seems like a slam dunk removal of a useless expensive feature.\n\nI agree with both, I just thought it might be interesting finding as this idiv might be (?) present in other common paths like ReadBuffer*() / PinBuffer() (some recent discussions, maybe on NUMA boxes), not just WAL recovery as it seems relatively easy to improve.\n\n-J.\n\n[1] - https://github.com/macdice/redo-bench\n[2] - https://fuhrwerks.com/csrg/info/93c40a660b6cdf74\n\n________________________________\nFrom: Thomas Munro <thomas.munro@gmail.com>\nSent: Tuesday, September 8, 2020 2:55 AM\nTo: Alvaro Herrera <alvherre@2ndquadrant.com>\nCc: Jakub Wartak <Jakub.Wartak@tomtom.com>; pgsql-hackers <pgsql-hackers@postgresql.org>\nSubject: Re: Division in dynahash.c due to HASH_FFACTOR\n\nOn Sat, Sep 5, 2020 at 2:34 AM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n> On 2020-Sep-04, Jakub Wartak wrote:\n> > After removing HASH_FFACTOR PostgreSQL still compiles... Would\n> > removing it break some external API/extensions ?\n>\n> FWIW, HASH_FFACTOR has *never* been used in Postgres core code.\n>\n> https://postgr.es/m/20160418180711.55ac82c0@fujitsu already reported\n> that this flag was unused a few years ago. And a search through\n> codesearch.debian.net shows that no software packaged by Debian uses\n> that flag either.\n>\n> *If* any third-party extension is using HASH_FFACTOR, it can easily be\n> unbroken by removing the flag or #defining it to zero; the removal would\n> only be a problem if anyone showed that there is a performance loss by\n> using the default fillfactor for some dynahash table instead of their\n> custom value.\n>\n> I think if we know that there's a 4% performance increase by removing\n> the division that comes with an ability to use a custom fillfactor that\n> nobody uses or has ever used, it makes sense to remove that ability.\n\nI think Tomas is right, and the correct fix for this would be to\ncompute it up front every time the hash table size changes, but since\napparently no one ever used it, +1 for just removing it and leaving it\nhard-coded.\n\nFor what it's worth, for dshash.c I just hard coded it to double the\nhash table size whenever the number of elements in a partition\nexceeded 75%. Popular hash tables in standard libraries seem to use\neither .75 or 1.0 as a default or only setting. There's probably room\nfor discussion about numbers in those ranges, but I think the concept\nof customisable load factors with a range much wider than that may be\nmore relevant for disk-based hash tables (like our hash indexes),\nwhich have very different economics. I think the name HASH_FFACTOR\nmay be a clue that this was possibly interference from disk-based hash\ntables from the same Berkeley people: rather than \"load factor\", the\nmore usual term (?) for nentries/nbuckets in memory-based hash tables\nas a way to model number of expected collisions, they called it \"fill\nfactor\", which I guess is because in disk-based designs your actually\nwant a certain rate of collisions, because you're working not with\nelements in an array and wanting to avoid collisions while not wasting\nspace, but rather with fixed sized buckets that you want to fill up,\nbut not overflow. </archeological-speculation-mode>\n\n> ... however, if we're really tense about improving some hash table's\n> performance, it might be worth trying to use simplehash.h instead of\n> dynahash.c for it.\n\nSure, but removing the dynahash IDIV also seems like a slam dunk\nremoval of a useless expensive feature.\n\n\n\n\n\n\n\n\nHi Thomas, Tomas :), Alvaro, hackers, \n\n\n\n>> > After removing HASH_FFACTOR PostgreSQL still compiles...  Would\n>> > removing it break some external API/extensions ?\n>>\n>> FWIW, HASH_FFACTOR has *never* been used in Postgres core code.\n[..]\n>> I think if we know that there's a 4% performance increase by removing\n>> the division that comes with an ability to use a custom fillfactor that\n>> nobody uses or has ever used, it makes sense to remove that ability.\n\n\nThomas wrote:\n\n>I think Tomas is right, and the correct fix for this would be to\n>compute it up front every time the hash table size changes, but since\n>apparently no one ever used it, +1 for just removing it and leaving it\n>hard-coded.\n[..]\n\n>For what it's worth, for dshash.c I just hard coded it to double the\n>hash table size whenever the number of elements in a partition\n>exceeded 75%.  Popular hash tables in standard libraries seem to use\n>either .75 or 1.0 as a default or only setting.  There's probably room\n>for discussion about numbers in those ranges, (..)\n\n\nTomas also asked the same \"what if you lower the fill factor, e.g. to 0.8? Does that improve performance or not?\" and got some interesting links for avoiding bias. I couldn't find any other simple way to benchmark a real impact of it other than checking\n DB crash-recovery (if anyone has some artificial workload generator with  PinBuffer->hash_search() please let me know).\n\n\n\nSo I've  been testing it using WAL crash-recovery using Thomas's approach [1]: always the same workload to reply, always on the same machine, same env: same 13GB WAL to recover, 8GB db, 24GB shared buffers on top of 128GB RAM, NVMe with fsync off to put\n dynahash as primary bottleneck (BufTableLookup()+smgropen()), append-only workload, gcc -O3: Results are <1st time is the WAL recovery timing, 2nd time is checkpoint before opening DB>. There were four measurements per each scenario, first one is cut off to\n avoid noise:\n\n\n1. DEF_FFACTOR=1 idiv on\n103.971, 3.719\n103.937, 3.683\n104.934, 3.691\n\n\n2. DEF_FFACTOR=1 idiv off\n100.565, 3.71\n101.595, 3.807\n100.794, 3.691\n\n\n3. DEF_FFACTOR=1.2 idiv on // some proof that nobody uses it\n\n1599552729.041 postmaster 94510 FATAL:  failed to initialize hash table \"SERIALIZABLEXID hash\"\n\n\n4. DEF_FFACTOR=0.8 idiv on // another proof ? The reason for below is that ffactor is long and as such cannot handle floats, if it would be float....\n\n\n\nProgram terminated with signal 8, Arithmetic exception.\n#0  0x00000000009a4119 in init_htab (nelem=4, hashp=0x17cd238) at dynahash.c:677\n677             nbuckets = next_pow2_int((nelem - 1) / hctl->ffactor + 1);\nMissing separate debuginfos, use: debuginfo-install glibc-2.17-292.180.amzn1.x86_64\n\n\n#0  0x00000000009a4119 in init_htab (nelem=4, hashp=0x17cd238) at dynahash.c:677\n#1  hash_create (tabname=tabname@entry=0xb77f9a \"Timezones\", nelem=nelem@entry=4, info=info@entry=0x7ffd3055cf30, flags=flags@entry=16) at dynahash.c:529\n#2  0x00000000009ecddf in init_timezone_hashtable () at pgtz.c:211\n#3  pg_tzset (name=name@entry=0xb49fd5 \"GMT\") at pgtz.c:248\n#4  0x00000000009ecfee in pg_timezone_initialize () at pgtz.c:372\n\n\n5. DEF_FFACTOR=1 idiv on // just in case reproducer to validate measurement #1\n\n104.333, 3.804\n104.313, 3.772\n103.951, 3.687\n\n\n6. DEF_FFACTOR=2 idiv on\n105.406, 3.783\n105.33, 3.721\n105.403, 3.777\n\n\n7. DEF_FFACTOR=4 idiv on\n105.803, 3.722\n105.73, 3.728\n106.104, 3.756\n\n\nSome notes: \n- SMgrRelationHash is initialized from start at 400, while DB here is small 8GB and has only couple of tables  -> no expansion needed in above test.\n- local backend private overflow hash table for buffers: PrivateRefCountHash is initialized at 100 and maybe it grows during\n\n- googling for DEF_FFACTOR I've found only 1 entry with value of <> 1 from 1993 (see this [2] , what's interesting is the same DEF_SEGSIZE value after all those years)\n\n\n\nAlvaro wrote:\n\n>> ... however, if we're really tense about improving some hash table's\n>> performance, it might be worth trying to use simplehash.h instead of\n>> dynahash.c for it.\n\n\nThomas wrote:\n\n> Sure, but removing the dynahash IDIV also seems like a slam dunk removal of a useless expensive feature.\n\nI agree with both, I just thought it might be interesting finding as this idiv might be (?) present in other common paths like ReadBuffer*() / PinBuffer() (some recent discussions, maybe on NUMA boxes), not just WAL recovery as it seems relatively easy\n to improve.\n\n\n\n-J.\n\n\n\n\n[1] - https://github.com/macdice/redo-bench\n\n\n[2] - \nhttps://fuhrwerks.com/csrg/info/93c40a660b6cdf74\n\n\n\n\n\n\nFrom: Thomas Munro <thomas.munro@gmail.com>\nSent: Tuesday, September 8, 2020 2:55 AM\nTo: Alvaro Herrera <alvherre@2ndquadrant.com>\nCc: Jakub Wartak <Jakub.Wartak@tomtom.com>; pgsql-hackers <pgsql-hackers@postgresql.org>\nSubject: Re: Division in dynahash.c due to HASH_FFACTOR\n \n\n\nOn Sat, Sep 5, 2020 at 2:34 AM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n> On 2020-Sep-04, Jakub Wartak wrote:\n> > After removing HASH_FFACTOR PostgreSQL still compiles...  Would\n> > removing it break some external API/extensions ?\n>\n> FWIW, HASH_FFACTOR has *never* been used in Postgres core code.\n>\n> https://postgr.es/m/20160418180711.55ac82c0@fujitsu already reported\n> that this flag was unused a few years ago.  And a search through\n> codesearch.debian.net shows that no software packaged by Debian uses\n> that flag either.\n>\n> *If* any third-party extension is using HASH_FFACTOR, it can easily be\n> unbroken by removing the flag or #defining it to zero; the removal would\n> only be a problem if anyone showed that there is a performance loss by\n> using the default fillfactor for some dynahash table instead of their\n> custom value.\n>\n> I think if we know that there's a 4% performance increase by removing\n> the division that comes with an ability to use a custom fillfactor that\n> nobody uses or has ever used, it makes sense to remove that ability.\n\nI think Tomas is right, and the correct fix for this would be to\ncompute it up front every time the hash table size changes, but since\napparently no one ever used it, +1 for just removing it and leaving it\nhard-coded.\n\nFor what it's worth, for dshash.c I just hard coded it to double the\nhash table size whenever the number of elements in a partition\nexceeded 75%.  Popular hash tables in standard libraries seem to use\neither .75 or 1.0 as a default or only setting.  There's probably room\nfor discussion about numbers in those ranges, but I think the concept\nof customisable load factors with a range much wider than that may be\nmore relevant for disk-based hash tables (like our hash indexes),\nwhich have very different economics.  I think the name HASH_FFACTOR\nmay be a clue that this was possibly interference from disk-based hash\ntables from the same Berkeley people: rather than \"load factor\", the\nmore usual term (?) for nentries/nbuckets in memory-based hash tables\nas a way to model number of expected collisions, they called it \"fill\nfactor\", which I guess is because in disk-based designs your actually\nwant a certain rate of collisions, because you're working not with\nelements in an array and wanting to avoid collisions while not wasting\nspace, but rather with fixed sized buckets that you want to fill up,\nbut not overflow.  </archeological-speculation-mode>\n\n> ... however, if we're really tense about improving some hash table's\n> performance, it might be worth trying to use simplehash.h instead of\n> dynahash.c for it.\n\nSure, but removing the dynahash IDIV also seems like a slam dunk\nremoval of a useless expensive feature.", "msg_date": "Tue, 8 Sep 2020 11:17:08 +0000", "msg_from": "Jakub Wartak <Jakub.Wartak@tomtom.com>", "msg_from_op": true, "msg_subject": "Re: Division in dynahash.c due to HASH_FFACTOR" }, { "msg_contents": "On Tue, Sep 8, 2020 at 11:17 PM Jakub Wartak <Jakub.Wartak@tomtom.com> wrote:\n> I agree with both, I just thought it might be interesting finding as this idiv might be (?) present in other common paths like ReadBuffer*() / PinBuffer() (some recent discussions, maybe on NUMA boxes), not just WAL recovery as it seems relatively easy to improve.\n\nI wrote a draft commit message for Jakub's proposed change (attached),\nand did a little bit of testing, but I haven't seen a case where it\nwins yet; I need to work on something else now but thought I'd share\nthis much anyway. One observation is that the rule in init_htab had\nbetter agree with the expansion rule in hash_search_with_hash_value,\notherwise you can size your hash table perfectly for n elements and\nthen it still has to expand when you insert the nth element, which is\nwhy I changed >= to >. Does this make sense? Oh man, I don't like\nthe mash-up of int, long, uint32, Size dynahash uses in various places\nand that are brought into relief by that comparison...", "msg_date": "Thu, 10 Sep 2020 14:54:17 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Division in dynahash.c due to HASH_FFACTOR" }, { "msg_contents": "On Thu, 10 Sep 2020 at 14:55, Thomas Munro <thomas.munro@gmail.com> wrote:\n>\n> I wrote a draft commit message for Jakub's proposed change (attached),\n> and did a little bit of testing, but I haven't seen a case where it\n> wins yet; I need to work on something else now but thought I'd share\n> this much anyway. One observation is that the rule in init_htab had\n> better agree with the expansion rule in hash_search_with_hash_value,\n> otherwise you can size your hash table perfectly for n elements and\n> then it still has to expand when you insert the nth element, which is\n> why I changed >= to >. Does this make sense? Oh man, I don't like\n> the mash-up of int, long, uint32, Size dynahash uses in various places\n> and that are brought into relief by that comparison...\n\nI just did some benchmarking with this patch using the same recovery\nbenchmark that I used in [1] and also the two patches that I posted in\n[2]. Additionally, I added a PANIC at the end of recovery so that I\ncould repeat the recovery over and over again with the same WAL.\n\nWithout 0001-Remove-custom-fill-factor-support-from-dynahash.c.patch,\nthe time in seconds reported for recovery was as follows:\n\nRun 1 65.2\nRun 2 65.41\nRun 3 65.1\nRun 4 64.86\nRun 5 62.29\nRun 6 67.06\nRun 7 63.35\nRun 8 63.1\nRun 9 62.8\nRun 10 62.15\n\nAvg 64.132\nMed 64.105\n\nAfter patching I got:\n\nRun 1 60.69\nRun 2 63.13\nRun 3 63.24\nRun 4 62.13\nRun 5 63.81\nRun 6 60.27\nRun 7 62.85\nRun 8 63.45\nRun 9 59.6\nRun 10 63.16\n\nAvg 62.233\nMed 62.99\n\nI was quite happy to see 59.6 seconds in there on run 9 as I'd been\ntrying hard to get that benchmark to go below 1 minute on my machine.\n\nperf appears to indicate that less time was spent in\nhash_search_with_hash_value()\n\nUnpatched:\n 26.96% postgres postgres [.] PageRepairFragmentation\n 12.07% postgres libc-2.31.so [.] __memmove_avx_unaligned_erms\n 10.13% postgres postgres [.] hash_search_with_hash_value\n 6.70% postgres postgres [.] XLogReadBufferExtended\n\nPatched:\n 27.70% postgres postgres [.] PageRepairFragmentation\n 13.50% postgres libc-2.31.so [.] __memmove_avx_unaligned_erms\n 9.63% postgres postgres [.] hash_search_with_hash_value\n 6.44% postgres postgres [.] XLogReadBufferExtended\n\nI looked over the patch and the only thing I saw was that we might\nalso want to remove the following line:\n\n#define DEF_FFACTOR 1 /* default fill factor */\n\nAlso, a couple of things I noticed when looking at performance\nprofiles in detail.\n\n1) The most expensive user of hash_search_with_hash_value() comes from\nBufTableLookup() which passes HASH_FIND as the HASHACTION.\n2) The code that was doing the divide in the unpatched version only\ntriggered when HASHACTION was HASH_ENTER or HASH_ENTER_NULL.\n\nThe 2nd most costly call to hash_search_with_hash_value() came in via\nhash_search() via smgropen(). That does use HASH_ENTER, which could\nhave triggered the divide code. The main caller of smgropen() was\nXLogReadBufferExtended().\n\nSo, it looks unlikely that any gains we are seeing are from improved\nbuffer lookups. It's more likely they're coming from more optimal\nXLogReadBufferExtended()\n\nDavid\n\n[1] https://www.postgresql.org/message-id/CAApHDvoKwqAzhiuxEt8jSquPJKDpH8DNUZDFUSX9P7DXrJdc3Q@mail.gmail.com\n[2] https://www.postgresql.org/message-id/CAApHDvo9n-nOb3b4PYFx%2Bw9mqd2SSUHm_oAs039eZnZLqFGcbQ%40mail.gmail.com\n\n\n", "msg_date": "Mon, 14 Sep 2020 23:34:53 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Division in dynahash.c due to HASH_FFACTOR" }, { "msg_contents": "On Mon, Sep 14, 2020 at 11:35 PM David Rowley <dgrowleyml@gmail.com> wrote:\n> I just did some benchmarking with this patch using the same recovery\n> benchmark that I used in [1] and also the two patches that I posted in\n> [2]. Additionally, I added a PANIC at the end of recovery so that I\n> could repeat the recovery over and over again with the same WAL.\n>\n> [data]\n\n N Min Max Median Avg Stddev\nx 10 62.15 67.06 64.86 64.132 1.6188528\n+ 10 59.6 63.81 63.13 62.233 1.4983031\nDifference at 95.0% confidence\n -1.899 +/- 1.46553\n -2.96108% +/- 2.28517%\n (Student's t, pooled s = 1.55974)\n\nThanks! Hmm, small but apparently significant and in line with\nJakub's report, and I suppose the effect will be greater with other\nnearby recovery performance patches applied that halve the times.\nAnnoyingly, I can't reproduce this speedup on my local i9-9900; maybe\nit requires a different CPU...\n\n> I looked over the patch and the only thing I saw was that we might\n> also want to remove the following line:\n>\n> #define DEF_FFACTOR 1 /* default fill factor */\n\nRight, thanks. Fixed in the attached.\n\n> The 2nd most costly call to hash_search_with_hash_value() came in via\n> hash_search() via smgropen(). That does use HASH_ENTER, which could\n> have triggered the divide code. The main caller of smgropen() was\n> XLogReadBufferExtended().\n>\n> So, it looks unlikely that any gains we are seeing are from improved\n> buffer lookups. It's more likely they're coming from more optimal\n> XLogReadBufferExtended()\n\nI think we call smgropen() twice for every buffer referenced in the\nWAL: XLogReadBufferExtended() and again in\nReadBufferWithoutRelcache(). We could reduce it to once with some\nrefactoring, but I am looking into whether I can reduce it to zero as\na side-effect of another change, more soon...", "msg_date": "Tue, 15 Sep 2020 09:56:16 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Division in dynahash.c due to HASH_FFACTOR" }, { "msg_contents": "On Tue, Sep 15, 2020 at 9:56 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n> > I looked over the patch and the only thing I saw was that we might\n> > also want to remove the following line:\n> >\n> > #define DEF_FFACTOR 1 /* default fill factor */\n>\n> Right, thanks. Fixed in the attached.\n\nPushed. Thanks Jakub, everyone.\n\nSeparately, we really should tidy up the int/long/uint32/size_t\nconfusion in this module. I know we have K&R C-era long-itude in\nnumerous other modules, but this one is a little more egregious in its\ndata type mixing.\n\n\n", "msg_date": "Sat, 19 Sep 2020 11:56:06 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Division in dynahash.c due to HASH_FFACTOR" }, { "msg_contents": "Thomas Munro <thomas.munro@gmail.com> writes:\n> Pushed. Thanks Jakub, everyone.\n\nBTW, looking over this patch, I wonder about\n\n /*\n * Can't split if running in partitioned mode, nor if frozen, nor if\n * table is the subject of any active hash_seq_search scans. Strange\n * order of these tests is to try to check cheaper conditions first.\n */\n if (!IS_PARTITIONED(hctl) && !hashp->frozen &&\n hctl->freeList[0].nentries > (long) (hctl->max_bucket + 1) &&\n !has_seq_scans(hashp))\n (void) expand_table(hashp);\n\nISTM that getting rid of the division obviates the concern that the\nnentries condition is too expensive, and therefore we should revert\nto checking it first, on the grounds that that condition is most\nlikely to fail.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 18 Sep 2020 21:11:46 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Division in dynahash.c due to HASH_FFACTOR" }, { "msg_contents": "I wrote:\n> ISTM that getting rid of the division obviates the concern that the\n> nentries condition is too expensive,\n\nAlso, we could make it slightly cheaper yet, by changing the condition\nto\n\n hctl->freeList[0].nentries > (long) (hctl->max_bucket)\n\nie drop the +1. I'd argue that this is actually a more faithful\nrendition of the previous condition, since what we had before was\nbasically\n\n hctl->freeList[0].nentries >= (long) (hctl->max_bucket + 1)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 18 Sep 2020 21:30:56 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Division in dynahash.c due to HASH_FFACTOR" }, { "msg_contents": "On Sat, Sep 19, 2020 at 1:30 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> I wrote:\n> > ISTM that getting rid of the division obviates the concern that the\n> > nentries condition is too expensive,\n\nTrue, that comment needed to go.\n\n> Also, we could make it slightly cheaper yet, by changing the condition\n> to\n>\n> hctl->freeList[0].nentries > (long) (hctl->max_bucket)\n>\n> ie drop the +1. I'd argue that this is actually a more faithful\n> rendition of the previous condition, since what we had before was\n> basically\n>\n> hctl->freeList[0].nentries >= (long) (hctl->max_bucket + 1)\n\nAgreed, and done. Thanks!\n\n\n", "msg_date": "Sat, 19 Sep 2020 15:55:24 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Division in dynahash.c due to HASH_FFACTOR" } ]
[ { "msg_contents": "hello, hackers.\n\nI found a comment error in buffer descriptors comment. The cache line size\nis 64 bytes, not 64 bits", "msg_date": "Fri, 4 Sep 2020 23:31:55 +0800", "msg_from": "Kelly Min <myzhmin@gmail.com>", "msg_from_op": true, "msg_subject": "\n =?UTF-8?Q?=5BPATCH=5D_Comments_related_to_=22_buffer_descriptors=E2=80=9C_?=\n\t=?UTF-8?Q?cache_line_size=22?=" }, { "msg_contents": "On Fri, Sep 4, 2020 at 11:31:55PM +0800, Kelly Min wrote:\n> hello, hackers.\n> \n> \n> I found a comment error in buffer descriptors comment. The cache line size is\n> 64 bytes, not 64 bits\n\nThanks, fix applied to all active branches.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Fri, 4 Sep 2020 13:28:11 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Comments related =?utf-8?Q?to_?=\n =?utf-8?Q?=22_buffer_descriptors=E2=80=9C?= cache line size\"" }, { "msg_contents": "On Sat, Sep 5, 2020 at 5:28 AM Bruce Momjian <bruce@momjian.us> wrote:\n> On Fri, Sep 4, 2020 at 11:31:55PM +0800, Kelly Min wrote:\n> > I found a comment error in buffer descriptors comment. The cache line size is\n> > 64 bytes, not 64 bits\n>\n> Thanks, fix applied to all active branches.\n\nI find it a bit strange that our PG_CACHE_LINE_SIZE macro is defined\nto be 128. Whether that exaggerated number (unless you're on POWER,\nwhere it's true) makes sense depends on what your goals are, as this\nusage of hard-coded 64 shows...\n\n\n", "msg_date": "Sat, 5 Sep 2020 08:26:06 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "\n =?UTF-8?Q?Re=3A_=5BPATCH=5D_Comments_related_to_=22_buffer_descriptors?=\n\t=?UTF-8?Q?=E2=80=9C_cache_line_size=22?=" } ]
[ { "msg_contents": "Hi hackers,\r\n\r\nI was wondering if there's a good reason in pg_dump getPublicationTables() \r\nto iterate through all tables one by one and querying to see if it has a \r\ncorresponding publication other than memory concerns?\r\n\r\nAttached is a patch to construct the publications by querying for all publications \r\nat once and then finding the corresponding tableInfo information in tblinfoindex. \r\n\r\nIt seems more likely that users will have a lot more tables than publications so \r\nthis should be a lot faster, especially when there's millions of tables.\r\n\r\nSetup: \r\ntime pg_dump --schema-only -d postgres -f dump.sql -v 2> dump.log\r\n10k tables, each table having its own publication.\r\n\r\nBefore patch:\r\nreal\t0m6.409s\r\nuser\t0m0.234s\r\nsys\t0m0.584s\r\n\r\nWith patch:\r\nreal\t0m5.483s\r\nuser\t0m0.399s\r\nsys\t0m0.443s\r\n\r\n10k tables, no publications.\r\n\r\nBefore patch:\r\nreal\t0m6.193s\r\nuser\t0m0.276s\r\nsys\t0m0.531s\r\n\r\nWith patch:\r\nreal\t0m5.261s\r\nuser\t0m0.254s\r\nsys\t0m0.377s\r\n\r\nThanks,\r\n\r\nJohn H", "msg_date": "Fri, 4 Sep 2020 18:03:39 +0000", "msg_from": "\"Hsu, John\" <hsuchen@amazon.com>", "msg_from_op": true, "msg_subject": "Improve pg_dump dumping publication tables" }, { "msg_contents": "The following review has been posted through the commitfest application:\nmake installcheck-world: tested, passed\nImplements feature: tested, passed\nSpec compliant: tested, passed\nDocumentation: not tested\n\nHi\r\n\r\nI applied the patch to PG master branch successfully and the patch seems to do as described. If there are a lot of tables created in the Postgres and only a few of them having publications, the getPublicationTables() function will loop through all the tables and check each one to see if it is the desired relation type and if it contains one or more publications. So potentially a lot of looping and checking may happen. In John's patch, all these looping and checking are replaced with one query that will return all the tables that have publications. One problem though, is that, if there are a million tables created in the server like you say and all of them have publications, the query can return a million rows, which will require a lot of memory on client side and the pg_dump client may need to handle this extreme case with proper pagination, which adds complexity to the function's logic. Existing logic does not have this problem, because it simply queries a table's publication one at a time and do it a million times.\r\n\r\nthank you\r\nCary Huang\r\nHighGo Software", "msg_date": "Tue, 13 Oct 2020 19:23:30 +0000", "msg_from": "Cary Huang <cary.huang@highgo.ca>", "msg_from_op": false, "msg_subject": "Re: Improve pg_dump dumping publication tables" }, { "msg_contents": "Hi Cary,\r\n\r\nThanks for taking a look. I agree there's a risk since there's more memory usage on client side, and if you're dumping say millions of publicationTables then that could be problematic. \r\nI'd like to think this isn't any riskier than existing pg_dump code such as in getTables(...) where presumably we would run into similar problems. \r\n\r\nCheers,\r\nJohn H", "msg_date": "Mon, 26 Oct 2020 21:43:59 +0000", "msg_from": "John Hsu <chenhao.john.hsu@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Improve pg_dump dumping publication tables" }, { "msg_contents": "\"Hsu, John\" <hsuchen@amazon.com> writes:\n> I was wondering if there's a good reason in pg_dump getPublicationTables() \n> to iterate through all tables one by one and querying to see if it has a \n> corresponding publication other than memory concerns?\n\nI just came across this entry in the CommitFest, and I see that it's\npractically the same as something I did in passing in 8e396a773.\nThe main difference is that I got rid of the server-side join, too,\nin favor of having getPublicationTables locate the PublicationInfo\nthat should have been created already by getPublications. (The\nimmediate rationale for that was to get the publication owner name\nfrom the PublicationInfo; but we'd have had to do that eventually\nanyway if we ever want to allow selective dumping of publications.)\n\nAnyway, I apologize for treading on your toes. If I'd noticed this\nthread earlier I would certainly have given you credit for being the\nfirst to have the idea.\n\nAs far as the memory argument goes, I'm not too concerned about it\nbecause both the PublicationRelInfo structs and the tuples of the\ntransient PGresult are pretty small. In principle if you had very\nmany entries in pg_publication_rel, but a selective dump was only\ninterested in a few of them, there might be an interesting amount of\nspace wasted here. But that argument fails because even a selective\ndump collects data about all tables, for reasons that are hard to get\naround. The incremental space usage for PublicationRelInfos seems\nunlikely to be significant compared to the per-table data we'd have\nanyway.\n\nI'll mark this CF entry \"withdrawn\", since it wasn't rejected\nexactly. Too bad we don't have a classification of \"superseded\nby events\", or something like that.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 15 Jan 2021 15:22:03 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Improve pg_dump dumping publication tables" } ]
[ { "msg_contents": "While playing around with clang's scan-build I noticed this warning:\n\nworker.c:2281:7: warning: Value stored to 'ping_sent' is never read\n ping_sent = true;\n ^ ~~~~\n\nAt first I thought it was a harmless unnecessary update, but looking\ncloser I wonder whether it isn't telling us there is a logic bug here.\nSpecifically, I wonder why the \"ping_sent\" variable is local to the\nloop starting at line 2084, rather than having the same lifespan as\n\"last_recv_timestamp\". Do we really want to forget that we sent a\nping anytime we have to wait for more data?\n\nIn fact, looking closer, it appears to me that\n\n(1) The \"ping_sent = false\" at line 2124 is also dead code, because\nping_sent could never be anything but false at this point;\n\n(2) The \"if (!ping_sent)\" at line 2274 is also dead code, because\nping_sent is still never anything but false at that point.\n\nIn short, we could remove the ping_sent variable entirely without\nchanging this code's behavior. I'm not 100% sure what semantics\nit's trying to achieve, but I don't think it's achieving them.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 04 Sep 2020 15:41:16 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Questionable ping logic in LogicalRepApplyLoop" }, { "msg_contents": "On 2020-Sep-04, Tom Lane wrote:\n\n> While playing around with clang's scan-build I noticed this warning:\n> \n> worker.c:2281:7: warning: Value stored to 'ping_sent' is never read\n> ping_sent = true;\n> ^ ~~~~\n> \n> At first I thought it was a harmless unnecessary update, but looking\n> closer I wonder whether it isn't telling us there is a logic bug here.\n> Specifically, I wonder why the \"ping_sent\" variable is local to the\n> loop starting at line 2084, rather than having the same lifespan as\n> \"last_recv_timestamp\". Do we really want to forget that we sent a\n> ping anytime we have to wait for more data?\n\nAh ... maybe this bug is the reason why the bug fixed by 470687b4a5bb\ndid not affect logical replication.\n\n> In short, we could remove the ping_sent variable entirely without\n> changing this code's behavior. I'm not 100% sure what semantics\n> it's trying to achieve, but I don't think it's achieving them.\n\nI imagine that moving the variable one block-scope outwards (together\nwith last_recv_timestamp) is what was intended.\n\n... oh look! commit 3f60f690fac1 moved last_recv_timestamp without\nrealizing that ping_sent had to get the same treatment.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 4 Sep 2020 16:41:47 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Questionable ping logic in LogicalRepApplyLoop" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> ... oh look! commit 3f60f690fac1 moved last_recv_timestamp without\n> realizing that ping_sent had to get the same treatment.\n\nHah, I wondered if something like that had happened, but I didn't\nget around to excavating in the git history yet. Thanks for doing so.\n\nWill push a fix later.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 04 Sep 2020 17:41:11 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Questionable ping logic in LogicalRepApplyLoop" } ]
[ { "msg_contents": "I discovered a problem today while trying to do a VPATH build on\na machine I don't use that often:\n\n$ make\n...\nIn file included from /home/tgl/pgsql/src/include/postgres.h:47,\n from /home/tgl/pgsql/src/common/hashfn.c:24:\n/home/tgl/pgsql/src/include/utils/elog.h:71:10: fatal error: utils/errcodes.h: No such file or directory\n 71 | #include \"utils/errcodes.h\"\n | ^~~~~~~~~~~~~~~~~~\ncompilation terminated.\n\nThe proximate problem is that src/include/utils/errcodes.h exists\nin the VPATH build directory, but it's a symlink pointing to\nsrc/backend/utils/errcodes.h in the build directory, which does not exist.\n\nAfter a bit of looking around, I think that the cause of that is this\nrule in src/backend/utils/Makefile:\n\n$(top_builddir)/src/include/utils/header-stamp: fmgr-stamp errcodes.h\n\tprereqdir=`cd '$(dir $<)' >/dev/null && pwd` && \\\n\tcd '$(dir $@)' && for file in fmgroids.h fmgrprotos.h errcodes.h; do \\\n\t rm -f $$file && $(LN_S) \"$$prereqdir/$$file\" . ; \\\n\tdone\n\ttouch $@\n\nThe last build I did on this machine was a non-VPATH build a few\nweeks ago. \"make distclean\" from that left behind an errcodes.h\nthat's still up to date, so make figured it didn't have to do\nanything, and the referent of the \"errcodes.h\" dependency here is\nthe errcodes.h in the source directory. On the other hand,\npg_proc.dat changed recently, so fmgr-stamp and related files\nwere considered out of date and rebuilt --- in the build tree.\nThus, the \"prereqdir\" in the above rule ends up pointing at\nsrc/backend/utils in the build tree, but while fmgroids.h and\nfmgrprotos.h do exist there, errcodes.h does not.\n\nThere are a couple different ways we might think about fixing\nthis. Maybe this specific rule is broken and needs to be fixed to\nnot assume that '$(dir $<)' is the same for all its dependencies.\nAlternatively, maybe the problem is that the derived files\nfmgr-stamp et al. should have been created in the source tree, even\nduring a VPATH build. (I have a vague recollection that we do it\nthat way for some derived files, but maybe that's out of date.)\n\nOf course, it might also be fair to argue that this scenario of\na source tree that has only some up-to-date derived files is\nnot supported/supportable. It definitely doesn't seem worth\na huge amount of effort to fix; but on the other hand the rule\nI cite above does seem to be assuming something it shouldn't.\n\nThoughts?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 04 Sep 2020 21:49:16 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Weird corner-case failure mode for VPATH builds" }, { "msg_contents": "On Fri, Sep 4, 2020 at 9:49 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> I discovered a problem today while trying to do a VPATH build on\n> a machine I don't use that often:\n>\n> $ make\n> ...\n> In file included from /home/tgl/pgsql/src/include/postgres.h:47,\n> from /home/tgl/pgsql/src/common/hashfn.c:24:\n> /home/tgl/pgsql/src/include/utils/elog.h:71:10: fatal error: utils/errcodes.h: No such file or directory\n> 71 | #include \"utils/errcodes.h\"\n> | ^~~~~~~~~~~~~~~~~~\n> compilation terminated.\n\nI think I've seen this before, but I don't have an opinion on how to fix it.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Fri, 11 Sep 2020 12:53:58 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Weird corner-case failure mode for VPATH builds" }, { "msg_contents": "On 2020-Sep-11, Robert Haas wrote:\n\n> On Fri, Sep 4, 2020 at 9:49 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > I discovered a problem today while trying to do a VPATH build on\n> > a machine I don't use that often:\n> >\n> > $ make\n> > ...\n> > In file included from /home/tgl/pgsql/src/include/postgres.h:47,\n> > from /home/tgl/pgsql/src/common/hashfn.c:24:\n> > /home/tgl/pgsql/src/include/utils/elog.h:71:10: fatal error: utils/errcodes.h: No such file or directory\n> > 71 | #include \"utils/errcodes.h\"\n> > | ^~~~~~~~~~~~~~~~~~\n> > compilation terminated.\n> \n> I think I've seen this before, but I don't have an opinion on how to fix it.\n\nMe too. It would be useful to have a way to report that build artifacts\nare in the source dir that should be in the build dir. I don't know if\nthis is in any way workable.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 11 Sep 2020 13:58:41 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Weird corner-case failure mode for VPATH builds" }, { "msg_contents": "Hi,\n\nOn 2020-09-11 13:58:41 -0300, Alvaro Herrera wrote:\n> On 2020-Sep-11, Robert Haas wrote:\n> \n> > On Fri, Sep 4, 2020 at 9:49 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > > I discovered a problem today while trying to do a VPATH build on\n> > > a machine I don't use that often:\n> > >\n> > > $ make\n> > > ...\n> > > In file included from /home/tgl/pgsql/src/include/postgres.h:47,\n> > > from /home/tgl/pgsql/src/common/hashfn.c:24:\n> > > /home/tgl/pgsql/src/include/utils/elog.h:71:10: fatal error: utils/errcodes.h: No such file or directory\n> > > 71 | #include \"utils/errcodes.h\"\n> > > | ^~~~~~~~~~~~~~~~~~\n> > > compilation terminated.\n> > \n> > I think I've seen this before, but I don't have an opinion on how to fix it.\n> \n> Me too. It would be useful to have a way to report that build artifacts\n> are in the source dir that should be in the build dir. I don't know if\n> this is in any way workable.\n\n\"git clean -nx\" should list them for vpath builds.\n\nRegards,\n\nAndres\n\n\n", "msg_date": "Fri, 11 Sep 2020 11:13:58 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Weird corner-case failure mode for VPATH builds" }, { "msg_contents": "On Fri, Sep 04, 2020 at 09:49:16PM -0400, Tom Lane wrote:\n> There are a couple different ways we might think about fixing\n> this. Maybe this specific rule is broken and needs to be fixed to\n> not assume that '$(dir $<)' is the same for all its dependencies.\n> Alternatively, maybe the problem is that the derived files\n> fmgr-stamp et al. should have been created in the source tree, even\n> during a VPATH build. (I have a vague recollection that we do it\n> that way for some derived files, but maybe that's out of date.)\n\nThe GNU make manual does recommend:\n\n GNU distributions usually contain some files which are not source files—for\n example, Info files, and the output from Autoconf, Automake, Bison or\n Flex. Since these files normally appear in the source directory, they should\n always appear in the source directory, not in the build directory. So\n Makefile rules to update them should put the updated files in the source\n directory.\n -- https://www.gnu.org/software/make/manual/html_node/Makefile-Basics.html\n\n> Of course, it might also be fair to argue that this scenario of\n> a source tree that has only some up-to-date derived files is\n> not supported/supportable. It definitely doesn't seem worth\n> a huge amount of effort to fix; but on the other hand the rule\n> I cite above does seem to be assuming something it shouldn't.\n\nI agree fixing this is low-priority.\n\n\n", "msg_date": "Tue, 13 Oct 2020 02:48:08 -0700", "msg_from": "Noah Misch <noah@leadboat.com>", "msg_from_op": false, "msg_subject": "Re: Weird corner-case failure mode for VPATH builds" } ]
[ { "msg_contents": "I propose the attached little patch to set the name of the memory \ncontext of an unnamed portal to \"<unnamed>\" instead of just an empty \nstring. Otherwise the debug memory context dump looks a little \nconfusing. We use this convention elsewhere for making unnamed \nstatements etc. more clearly visible.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Sat, 5 Sep 2020 08:14:14 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Use <unnamed> for name of unnamed portal's memory context" }, { "msg_contents": "so 5. 9. 2020 v 8:14 odesílatel Peter Eisentraut <\npeter.eisentraut@2ndquadrant.com> napsal:\n\n> I propose the attached little patch to set the name of the memory\n> context of an unnamed portal to \"<unnamed>\" instead of just an empty\n> string. Otherwise the debug memory context dump looks a little\n> confusing. We use this convention elsewhere for making unnamed\n> statements etc. more clearly visible.\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\nso 5. 9. 2020 v 8:14 odesílatel Peter Eisentraut <peter.eisentraut@2ndquadrant.com> napsal:I propose the attached little patch to set the name of the memory \ncontext of an unnamed portal to \"<unnamed>\" instead of just an empty \nstring.  Otherwise the debug memory context dump looks a little \nconfusing.  We use this convention elsewhere for making unnamed \nstatements etc. more clearly visible.+1Pavel\n\n-- \nPeter Eisentraut              http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Sat, 5 Sep 2020 08:24:13 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Use <unnamed> for name of unnamed portal's memory context" }, { "msg_contents": "On Sat, Sep 5, 2020 at 8:25 AM Pavel Stehule <pavel.stehule@gmail.com> wrote:\n>\n> so 5. 9. 2020 v 8:14 odesílatel Peter Eisentraut <peter.eisentraut@2ndquadrant.com> napsal:\n>>\n>> I propose the attached little patch to set the name of the memory\n>> context of an unnamed portal to \"<unnamed>\" instead of just an empty\n>> string. Otherwise the debug memory context dump looks a little\n>> confusing. We use this convention elsewhere for making unnamed\n>> statements etc. more clearly visible.\n>\n>\n> +1\n\n+1 too, and obviously patch looks good.\n\n\n", "msg_date": "Sat, 5 Sep 2020 08:55:06 +0200", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Use <unnamed> for name of unnamed portal's memory context" }, { "msg_contents": "Julien Rouhaud <rjuju123@gmail.com> writes:\n> +1 too, and obviously patch looks good.\n\nThe adjacent comment needs updating.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 05 Sep 2020 11:10:20 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Use <unnamed> for name of unnamed portal's memory context" }, { "msg_contents": "On 2020-09-05 17:10, Tom Lane wrote:\n> Julien Rouhaud <rjuju123@gmail.com> writes:\n>> +1 too, and obviously patch looks good.\n> \n> The adjacent comment needs updating.\n\ncommitted with that change\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 8 Sep 2020 17:25:48 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: Use <unnamed> for name of unnamed portal's memory context" } ]
[ { "msg_contents": "scan-build complains that \"exists = false\" is a dead store,\nwhich it is:\n\nprocess_target_file(const char *path, file_type_t type, size_t oldsize,\n const char *link_target)\n{\n bool exists;\n ...\n\n if (lstat(localpath, &statbuf) < 0)\n {\n if (errno != ENOENT)\n pg_fatal(\"could not stat file \\\"%s\\\": %s\\n\",\n localpath, strerror(errno));\n\n exists = false;\n }\n\n ...\n exists = (bsearch(&key_ptr, map->array, map->narray, sizeof(file_entry_t *),\n path_cmp) != NULL);\n\nIt looks to me like we could replace \"exists = false\" with \"return\",\nrather than uselessly constructing a FILE_ACTION_REMOVE entry for\na file we've already proven is not there. This seems to have been\ncopy-and-pasted from process_source_file, without much thought for\nthe fact that the situations are quite different.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 05 Sep 2020 14:08:40 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Dubious code in pg_rewind's process_target_file()" }, { "msg_contents": "I wrote:\n> It looks to me like we could replace \"exists = false\" with \"return\",\n> rather than uselessly constructing a FILE_ACTION_REMOVE entry for\n> a file we've already proven is not there.\n\nOr actually, maybe we should just drop the lstat call altogether?\nAFAICS it's 99.99% redundant with the lstat that traverse_datadir\nhas done nanoseconds before. Yeah, maybe somebody managed to drop\nthe file in between, but the FILE_ACTION_REMOVE code would have to\ndeal with such cases anyway in case a drop occurs later.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 05 Sep 2020 14:18:29 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Dubious code in pg_rewind's process_target_file()" }, { "msg_contents": "On 05/09/2020 21:18, Tom Lane wrote:\n> I wrote:\n>> It looks to me like we could replace \"exists = false\" with \"return\",\n>> rather than uselessly constructing a FILE_ACTION_REMOVE entry for\n>> a file we've already proven is not there.\n> \n> Or actually, maybe we should just drop the lstat call altogether?\n> AFAICS it's 99.99% redundant with the lstat that traverse_datadir\n> has done nanoseconds before. Yeah, maybe somebody managed to drop\n> the file in between, but the FILE_ACTION_REMOVE code would have to\n> deal with such cases anyway in case a drop occurs later.\n\nAgreed, the lstat() doesn't do anything interesting.\n\nThis is refactored away by the patches discussed at \nhttps://www.postgresql.org/message-id/f155aab5-1323-8d0c-9e3b-32703124bf00%40iki.fi. \nBut maybe we should still clean it up in the back-branches.\n\n- Heikki\n\n\n", "msg_date": "Sun, 6 Sep 2020 17:54:22 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Dubious code in pg_rewind's process_target_file()" }, { "msg_contents": "Heikki Linnakangas <hlinnaka@iki.fi> writes:\n> On 05/09/2020 21:18, Tom Lane wrote:\n>> Or actually, maybe we should just drop the lstat call altogether?\n\n> Agreed, the lstat() doesn't do anything interesting.\n> This is refactored away by the patches discussed at \n> https://www.postgresql.org/message-id/f155aab5-1323-8d0c-9e3b-32703124bf00%40iki.fi. \n> But maybe we should still clean it up in the back-branches.\n\nAh, I'd not been paying much attention to that work, but I\nsee you are getting rid of the lstat().\n\nI propose to remove the lstat() in the back branches, but not touch\nHEAD so as not to cause extra merge effort for your patch.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 06 Sep 2020 11:06:59 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Dubious code in pg_rewind's process_target_file()" }, { "msg_contents": "On 06/09/2020 18:06, Tom Lane wrote:\n> Heikki Linnakangas <hlinnaka@iki.fi> writes:\n>> On 05/09/2020 21:18, Tom Lane wrote:\n>>> Or actually, maybe we should just drop the lstat call altogether?\n> \n>> Agreed, the lstat() doesn't do anything interesting.\n>> This is refactored away by the patches discussed at\n>> https://www.postgresql.org/message-id/f155aab5-1323-8d0c-9e3b-32703124bf00%40iki.fi.\n>> But maybe we should still clean it up in the back-branches.\n> \n> Ah, I'd not been paying much attention to that work, but I\n> see you are getting rid of the lstat().\n> \n> I propose to remove the lstat() in the back branches, but not touch\n> HEAD so as not to cause extra merge effort for your patch.\n\nThanks! Feel free to push it to HEAD, too, the merge conflict will be \ntrivial to resolve.\n\n- Heikki\n\n\n", "msg_date": "Sun, 6 Sep 2020 18:13:48 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Dubious code in pg_rewind's process_target_file()" }, { "msg_contents": "Heikki Linnakangas <hlinnaka@iki.fi> writes:\n> On 06/09/2020 18:06, Tom Lane wrote:\n>> I propose to remove the lstat() in the back branches, but not touch\n>> HEAD so as not to cause extra merge effort for your patch.\n\n> Thanks! Feel free to push it to HEAD, too, the merge conflict will be \n> trivial to resolve.\n\nOK, done that way.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 06 Sep 2020 11:51:25 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Dubious code in pg_rewind's process_target_file()" } ]
[ { "msg_contents": "Hi Juan,\n\nThis is only a suggestion, if you find it appropriate.\nWe could use a little cut tail in get_dirent_type function.\n\nTry to avoid add padding, when modifying or adding fields.\nstruct dirent\n {\n long d_ino;\n unsigned short d_reclen;\n unsigned short d_namlen;\n+ unsigned char d_type;\n char d_name[MAX_PATH];\n };\n\nOr even better if possible:\nstruct dirent\n {\n char d_name[MAX_PATH];\n long d_ino;\n unsigned short d_reclen;\n unsigned short d_namlen;\n unsigned char d_type;\n };\n\nregards,\nRanier Vilela", "msg_date": "Sat, 5 Sep 2020 15:58:51 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Re: A micro-optimisation for walkdir()" } ]
[ { "msg_contents": "I was wondering if I could just add minvfunc, and have the rest of the m*\nfunctions be assumed to be the same as their non-moving counterparts.\nApparently the answer is 'no'. But in the process, I found a bad error\nmessage. When omitting mfinalfunc when there is a finalfunc, I get the\nerror:\n\n\"ERROR: moving-aggregate implementation returns type jj_state, but plain\nimplementation returns type jj_state.\" A rather peculiar\ncomplaint, analogous to the infamous \"something failed: Success\".\n\nLooking at the code, it seems we are testing rettype != finaltype, but\nreporting aggmTransType and aggTransType. Why aren't we reporting what we\nare testing?\n\nWith the attached patch, it gives the more sensible \"ERROR:\n moving-aggregate implementation returns type jj_state, but plain\nimplementation returns type numeric.\"\n\nCheers,\n\nJeff", "msg_date": "Sun, 6 Sep 2020 12:07:16 -0400", "msg_from": "Jeff Janes <jeff.janes@gmail.com>", "msg_from_op": true, "msg_subject": "moving aggregate bad error message" }, { "msg_contents": "Jeff Janes <jeff.janes@gmail.com> writes:\n> Looking at the code, it seems we are testing rettype != finaltype, but\n> reporting aggmTransType and aggTransType. Why aren't we reporting what we\n> are testing?\n\nSilly thinko, apparently. Your fix looks right, will push.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 06 Sep 2020 12:41:41 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: moving aggregate bad error message" } ]
[ { "msg_contents": "Following a bulk load, a CLUSTER command run by a maintenance script crashed.\nThis is currently reproducible on that instance, so please suggest if I can\nprovide more info.\n\n< 2020-09-06 15:44:16.369 MDT >LOG: background worker \"parallel worker\" (PID 2576) was terminated by signal 6: Aborted\n< 2020-09-06 15:44:16.369 MDT >DETAIL: Failed process was running: CLUSTER pg_attribute USING pg_attribute_relid_attnam_index\n\nThe crash happens during:\nts=# REINDEX INDEX pg_attribute_relid_attnum_index;\n..but not:\nts=# REINDEX INDEX pg_attribute_relid_attnam_index ;\n\n pg_catalog | pg_attribute_relid_attnam_index | index | postgres | pg_attribute | permanent | 31 MB | \n pg_catalog | pg_attribute_relid_attnum_index | index | postgres | pg_attribute | permanent | 35 MB | \n\nI suspect\n|commit c6b92041d Skip WAL for new relfilenodes, under wal_level=minimal.\n\nIn fact, I set wal_level=minimal for the bulk load. Note also:\n override | data_checksums | on\n configuration file | checkpoint_timeout | 60\n configuration file | maintenance_work_mem | 1048576\n configuration file | max_wal_senders | 0\n configuration file | wal_compression | on\n configuration file | wal_level | minimal\n configuration file | fsync | off\n configuration file | full_page_writes | off\n default | server_version | 13beta3\n\n(gdb) bt\n#0 0x00007ff9999ad387 in raise () from /lib64/libc.so.6\n#1 0x00007ff9999aea78 in abort () from /lib64/libc.so.6\n#2 0x0000000000921da5 in ExceptionalCondition (conditionName=conditionName@entry=0xad4078 \"relcache_verdict == RelFileNodeSkippingWAL(relation->rd_node)\", errorType=errorType@entry=0x977f49 \"FailedAssertion\", \n fileName=fileName@entry=0xad3068 \"relcache.c\", lineNumber=lineNumber@entry=2976) at assert.c:67\n#3 0x000000000091a08b in AssertPendingSyncConsistency (relation=0x7ff99c2a70b8) at relcache.c:2976\n#4 AssertPendingSyncs_RelationCache () at relcache.c:3036\n#5 0x000000000058e591 in smgrDoPendingSyncs (isCommit=isCommit@entry=true, isParallelWorker=isParallelWorker@entry=true) at storage.c:685\n#6 0x000000000053b1a4 in CommitTransaction () at xact.c:2118\n#7 0x000000000053b826 in EndParallelWorkerTransaction () at xact.c:5300\n#8 0x000000000052fcf7 in ParallelWorkerMain (main_arg=<optimized out>) at parallel.c:1479\n#9 0x000000000076047a in StartBackgroundWorker () at bgworker.c:813\n#10 0x000000000076d88d in do_start_bgworker (rw=0x23ac110) at postmaster.c:5865\n#11 maybe_start_bgworkers () at postmaster.c:6091\n#12 0x000000000076e43e in sigusr1_handler (postgres_signal_arg=<optimized out>) at postmaster.c:5260\n#13 <signal handler called>\n#14 0x00007ff999a6c983 in __select_nocancel () from /lib64/libc.so.6\n#15 0x00000000004887bc in ServerLoop () at postmaster.c:1691\n#16 0x000000000076fb45 in PostmasterMain (argc=argc@entry=3, argv=argv@entry=0x237d280) at postmaster.c:1400\n#17 0x000000000048a83d in main (argc=3, argv=0x237d280) at main.c:210\n\n(gdb) bt f\n...\n#4 AssertPendingSyncs_RelationCache () at relcache.c:3036\n status = {hashp = 0x23cba50, curBucket = 449, curEntry = 0x0}\n locallock = <optimized out>\n rels = 0x23ff018\n maxrels = <optimized out>\n nrels = 0\n idhentry = <optimized out>\n i = <optimized out>\n#5 0x000000000058e591 in smgrDoPendingSyncs (isCommit=isCommit@entry=true, isParallelWorker=isParallelWorker@entry=true) at storage.c:685\n pending = <optimized out>\n nrels = 0\n maxrels = 0\n srels = 0x0\n scan = {hashp = 0x23edf60, curBucket = 9633000, curEntry = 0xe01600 <TopTransactionStateData>}\n pendingsync = <optimized out>\n#6 0x000000000053b1a4 in CommitTransaction () at xact.c:2118\n s = 0xe01600 <TopTransactionStateData>\n latestXid = <optimized out>\n is_parallel_worker = true\n __func__ = \"CommitTransaction\"\n\n\n\n", "msg_date": "Sun, 6 Sep 2020 21:37:37 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": true, "msg_subject": "v13: CLUSTER segv with wal_level=minimal and parallel index creation" }, { "msg_contents": "This is easily reproduced, at least on pg_attribute\n\n[pryzbyj@localhost ~]$ /usr/pgsql-13/bin/initdb -D pgsql13.dat\n[pryzbyj@localhost ~]$ /usr/pgsql-13/bin/postgres -D pgsql13.dat -c logging_collector=off -c port=5678 -c unix_socket_directories=/tmp -c wal-level=minimal -c max_wal_senders=0&\n[pryzbyj@localhost ~]$ psql -h /tmp -p 5678 postgres -c \"SET min_parallel_table_scan_size=0\" -c \"SET client_min_messages=debug\" -c \"REINDEX INDEX pg_attribute_relid_attnum_index\"\nSET\nSET\nDEBUG: building index \"pg_attribute_relid_attnum_index\" on table \"pg_attribute\" with request for 1 parallel worker\nTRAP: FailedAssertion(\"relcache_verdict == RelFileNodeSkippingWAL(relation->rd_node)\", File: \"relcache.c\", Line: 2976)\npostgres: parallel worker for PID 9637 (ExceptionalCondition+0x66)[0x921d86]\npostgres: parallel worker for PID 9637 (AssertPendingSyncs_RelationCache+0x1db)[0x91a08b]\npostgres: parallel worker for PID 9637 (smgrDoPendingSyncs+0x71)[0x58e591]\npostgres: parallel worker for PID 9637 [0x53b1a4]\npostgres: parallel worker for PID 9637 (EndParallelWorkerTransaction+0x16)[0x53b826]\npostgres: parallel worker for PID 9637 (ParallelWorkerMain+0x437)[0x52fcf7]\npostgres: parallel worker for PID 9637 (StartBackgroundWorker+0x25a)[0x76047a]\npostgres: parallel worker for PID 9637 [0x76d88d]\npostgres: parallel worker for PID 9637 [0x76e43e]\n/lib64/libpthread.so.0(+0xf630)[0x7f46d4b47630]\n/lib64/libc.so.6(__select+0x13)[0x7f46d26ba983]\npostgres: parallel worker for PID 9637 [0x4887bc]\npostgres: parallel worker for PID 9637 (PostmasterMain+0x1165)[0x76fb45]\npostgres: parallel worker for PID 9637 (main+0x70d)[0x48a83d]\n/lib64/libc.so.6(__libc_start_main+0xf5)[0x7f46d25e7555]\n\n-- \nJustin\n\n\n", "msg_date": "Sun, 6 Sep 2020 22:34:51 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": true, "msg_subject": "Re: v13: CLUSTER segv with wal_level=minimal and parallel index\n creation" }, { "msg_contents": "Justin Pryzby <pryzby@telsasoft.com> writes:\n> This is easily reproduced, at least on pg_attribute\n\nYeah, duplicated here. The assertion (not SIGSEGV) is in code\nadded by c6b92041d, so it seems clearly an open issue for v13.\n\nI did not check to see what happens in a non-assert build.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 07 Sep 2020 00:33:03 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: v13: CLUSTER segv with wal_level=minimal and parallel index\n creation" }, { "msg_contents": "At Mon, 07 Sep 2020 00:33:03 -0400, Tom Lane <tgl@sss.pgh.pa.us> wrote in \n> Justin Pryzby <pryzby@telsasoft.com> writes:\n> > This is easily reproduced, at least on pg_attribute\n\nThanks for the repro.\n\n> Yeah, duplicated here. The assertion (not SIGSEGV) is in code\n> added by c6b92041d, so it seems clearly an open issue for v13.\n> \n> I did not check to see what happens in a non-assert build.\n\nThe cause is that the worker had received pending-sync entry correctly\nbut not never created a relcache entry for the relation using\nRelationBuildDesc. So the rd_firstRelfilenodeSubid is not correctly\nset.\n\nI'm investigating it.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Mon, 07 Sep 2020 13:45:28 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: v13: CLUSTER segv with wal_level=minimal and parallel index\n creation" }, { "msg_contents": "At Mon, 07 Sep 2020 13:45:28 +0900 (JST), Kyotaro Horiguchi <horikyota.ntt@gmail.com> wrote in \n> The cause is that the worker had received pending-sync entry correctly\n> but not never created a relcache entry for the relation using\n> RelationBuildDesc. So the rd_firstRelfilenodeSubid is not correctly\n> set.\n> \n> I'm investigating it.\n\nRelcaches are loaded from a file with old content at parallel worker\nstartup. The relcache entry is corrected by invalidation at taking a\nlock but pending syncs are not considered.\n\nSince parallel workers don't access the files so we can just ignore\nthe assertion safely, but I want to rd_firstRelfilenodeSubid flag at\ninvalidation, as attached PoC patch.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center", "msg_date": "Mon, 07 Sep 2020 17:40:36 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: v13: CLUSTER segv with wal_level=minimal and parallel index\n creation" }, { "msg_contents": "On Mon, Sep 07, 2020 at 05:40:36PM +0900, Kyotaro Horiguchi wrote:\n> At Mon, 07 Sep 2020 13:45:28 +0900 (JST), Kyotaro Horiguchi <horikyota.ntt@gmail.com> wrote in \n> > The cause is that the worker had received pending-sync entry correctly\n> > but not never created a relcache entry for the relation using\n> > RelationBuildDesc. So the rd_firstRelfilenodeSubid is not correctly\n> > set.\n> > \n> > I'm investigating it.\n> \n> Relcaches are loaded from a file with old content at parallel worker\n> startup. The relcache entry is corrected by invalidation at taking a\n> lock but pending syncs are not considered.\n> \n> Since parallel workers don't access the files so we can just ignore\n> the assertion safely, but I want to rd_firstRelfilenodeSubid flag at\n> invalidation, as attached PoC patch.\n\n> [patch: When RelationInitPhysicalAddr() handles a mapped relation, re-fill\n> rd_firstRelfilenodeSubid from RelFileNodeSkippingWAL(), like\n> RelationBuildDesc() would do.]\n\nAs a PoC, this looks promising. Thanks. Would you add a test case such that\nthe following demonstrates the bug in the absence of your PoC?\n\n printf '%s\\n%s\\n%s\\n' 'log_statement = all' 'wal_level = minimal' 'max_wal_senders = 0' >/tmp/minimal.conf\n make check TEMP_CONFIG=/tmp/minimal.conf\n\nPlease have the test try both a nailed-and-mapped relation and a \"nailed, but\nnot mapped\" relation. I am fairly confident that your PoC fixes the former\ncase, but the latter may need additional code.\n\n\n", "msg_date": "Mon, 7 Sep 2020 02:32:55 -0700", "msg_from": "Noah Misch <noah@leadboat.com>", "msg_from_op": false, "msg_subject": "Re: v13: CLUSTER segv with wal_level=minimal and parallel index\n creation" }, { "msg_contents": "At Mon, 7 Sep 2020 02:32:55 -0700, Noah Misch <noah@leadboat.com> wrote in \n> On Mon, Sep 07, 2020 at 05:40:36PM +0900, Kyotaro Horiguchi wrote:\n> > At Mon, 07 Sep 2020 13:45:28 +0900 (JST), Kyotaro Horiguchi <horikyota.ntt@gmail.com> wrote in \n> > > The cause is that the worker had received pending-sync entry correctly\n> > > but not never created a relcache entry for the relation using\n> > > RelationBuildDesc. So the rd_firstRelfilenodeSubid is not correctly\n> > > set.\n> > > \n> > > I'm investigating it.\n> > \n> > Relcaches are loaded from a file with old content at parallel worker\n> > startup. The relcache entry is corrected by invalidation at taking a\n> > lock but pending syncs are not considered.\n> > \n> > Since parallel workers don't access the files so we can just ignore\n> > the assertion safely, but I want to rd_firstRelfilenodeSubid flag at\n> > invalidation, as attached PoC patch.\n> \n> > [patch: When RelationInitPhysicalAddr() handles a mapped relation, re-fill\n> > rd_firstRelfilenodeSubid from RelFileNodeSkippingWAL(), like\n> > RelationBuildDesc() would do.]\n> \n> As a PoC, this looks promising. Thanks. Would you add a test case such that\n> the following demonstrates the bug in the absence of your PoC?\n> \n> printf '%s\\n%s\\n%s\\n' 'log_statement = all' 'wal_level = minimal' 'max_wal_senders = 0' >/tmp/minimal.conf\n> make check TEMP_CONFIG=/tmp/minimal.conf\n\nMmm. I was close to add some tests to 018_wal_optimize.pl but your\nsuggestion seems better. I added several ines to create_index.sql.\n\n> Please have the test try both a nailed-and-mapped relation and a \"nailed, but\n> not mapped\" relation. I am fairly confident that your PoC fixes the former\n> case, but the latter may need additional code.\n\nMmm. You're right. I choosed pg_amproc_fam_proc_index as\nnailed-but-not-mapped index.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center", "msg_date": "Tue, 08 Sep 2020 09:13:53 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: v13: CLUSTER segv with wal_level=minimal and parallel index\n creation" }, { "msg_contents": "At Tue, 08 Sep 2020 09:13:53 +0900 (JST), Kyotaro Horiguchi <horikyota.ntt@gmail.com> wrote in \n> At Mon, 7 Sep 2020 02:32:55 -0700, Noah Misch <noah@leadboat.com> wrote in \n> > As a PoC, this looks promising. Thanks. Would you add a test case such that\n> > the following demonstrates the bug in the absence of your PoC?\n> > \n> > printf '%s\\n%s\\n%s\\n' 'log_statement = all' 'wal_level = minimal' 'max_wal_senders = 0' >/tmp/minimal.conf\n> > make check TEMP_CONFIG=/tmp/minimal.conf\n> \n> Mmm. I was close to add some tests to 018_wal_optimize.pl but your\n> suggestion seems better. I added several ines to create_index.sql.\n> \n> > Please have the test try both a nailed-and-mapped relation and a \"nailed, but\n> > not mapped\" relation. I am fairly confident that your PoC fixes the former\n> > case, but the latter may need additional code.\n> \n> Mmm. You're right. I choosed pg_amproc_fam_proc_index as\n> nailed-but-not-mapped index.\n\nI fixed a typo (s/staring/starting/).\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center", "msg_date": "Tue, 08 Sep 2020 10:43:32 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: v13: CLUSTER segv with wal_level=minimal and parallel index\n creation" }, { "msg_contents": "On Tue, Sep 08, 2020 at 10:43:32AM +0900, Kyotaro Horiguchi wrote:\n> At Tue, 08 Sep 2020 09:13:53 +0900 (JST), Kyotaro Horiguchi <horikyota.ntt@gmail.com> wrote in \n> > At Mon, 7 Sep 2020 02:32:55 -0700, Noah Misch <noah@leadboat.com> wrote in \n> > > As a PoC, this looks promising. Thanks. Would you add a test case such that\n> > > the following demonstrates the bug in the absence of your PoC?\n> > > \n> > > printf '%s\\n%s\\n%s\\n' 'log_statement = all' 'wal_level = minimal' 'max_wal_senders = 0' >/tmp/minimal.conf\n> > > make check TEMP_CONFIG=/tmp/minimal.conf\n> > \n> > Mmm. I was close to add some tests to 018_wal_optimize.pl but your\n> > suggestion seems better. I added several ines to create_index.sql.\n> > \n> > > Please have the test try both a nailed-and-mapped relation and a \"nailed, but\n> > > not mapped\" relation. I am fairly confident that your PoC fixes the former\n> > > case, but the latter may need additional code.\n> > \n> > Mmm. You're right. I choosed pg_amproc_fam_proc_index as\n> > nailed-but-not-mapped index.\n> \n> I fixed a typo (s/staring/starting/).\n\nAt a glance, this looks reasonable. If a closer look doesn't reveal problems,\nI'll push this.\n\n\n", "msg_date": "Mon, 7 Sep 2020 19:47:09 -0700", "msg_from": "Noah Misch <noah@leadboat.com>", "msg_from_op": false, "msg_subject": "Re: v13: CLUSTER segv with wal_level=minimal and parallel index\n creation" }, { "msg_contents": "On Mon, Sep 07, 2020 at 07:47:09PM -0700, Noah Misch wrote:\n> On Tue, Sep 08, 2020 at 10:43:32AM +0900, Kyotaro Horiguchi wrote:\n> > At Tue, 08 Sep 2020 09:13:53 +0900 (JST), Kyotaro Horiguchi <horikyota.ntt@gmail.com> wrote in \n> > > At Mon, 7 Sep 2020 02:32:55 -0700, Noah Misch <noah@leadboat.com> wrote in \n> > > > As a PoC, this looks promising. Thanks. Would you add a test case such that\n> > > > the following demonstrates the bug in the absence of your PoC?\n> > > > \n> > > > printf '%s\\n%s\\n%s\\n' 'log_statement = all' 'wal_level = minimal' 'max_wal_senders = 0' >/tmp/minimal.conf\n> > > > make check TEMP_CONFIG=/tmp/minimal.conf\n> > > \n> > > Mmm. I was close to add some tests to 018_wal_optimize.pl but your\n> > > suggestion seems better. I added several ines to create_index.sql.\n\nAfter looking closer, I've moved the test to reindex_catalog.sql; see that\nfile's header comment for the reasons. One now needs this command:\n\n printf '%s\\n%s\\n%s\\n' 'log_statement = all' 'wal_level = minimal' 'max_wal_senders = 0' >/tmp/minimal.conf\n make check-tests TESTS=reindex_catalog TEMP_CONFIG=/tmp/minimal.conf\n\n> > > > Please have the test try both a nailed-and-mapped relation and a \"nailed, but\n> > > > not mapped\" relation. I am fairly confident that your PoC fixes the former\n> > > > case, but the latter may need additional code.\n> > > \n> > > Mmm. You're right. I choosed pg_amproc_fam_proc_index as\n> > > nailed-but-not-mapped index.\n> > \n> > I fixed a typo (s/staring/starting/).\n> \n> At a glance, this looks reasonable. If a closer look doesn't reveal problems,\n> I'll push this.\n\nRelationBuildDesc() calls RelationInitPhysicalAddr(), so RelationBuildDesc()\ncan stop calling RelFileNodeSkippingWAL(). The attached version makes it so,\nand I plan to push it.", "msg_date": "Tue, 8 Sep 2020 21:05:43 -0700", "msg_from": "Noah Misch <noah@leadboat.com>", "msg_from_op": false, "msg_subject": "Re: v13: CLUSTER segv with wal_level=minimal and parallel index\n creation" }, { "msg_contents": "Thank you for the checking.\n\nAt Tue, 8 Sep 2020 21:05:43 -0700, Noah Misch <noah@leadboat.com> wrote in \n> On Mon, Sep 07, 2020 at 07:47:09PM -0700, Noah Misch wrote:\n> After looking closer, I've moved the test to reindex_catalog.sql; see that\n> file's header comment for the reasons. One now needs this command:\n> \n> printf '%s\\n%s\\n%s\\n' 'log_statement = all' 'wal_level = minimal' 'max_wal_senders = 0' >/tmp/minimal.conf\n> make check-tests TESTS=reindex_catalog TEMP_CONFIG=/tmp/minimal.conf\n\nI missed the file. It is surely the best place.\n\n> RelationBuildDesc() calls RelationInitPhysicalAddr(), so RelationBuildDesc()\n> can stop calling RelFileNodeSkippingWAL(). The attached version makes it so,\n> and I plan to push it.\n\nSure. relNode is filled with zeros so RelationInitPhysicalAddr() works\ncorrectly for RelationBuildDesc().\n\nBoth changes look good to me.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Wed, 09 Sep 2020 14:40:37 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: v13: CLUSTER segv with wal_level=minimal and parallel index\n creation" }, { "msg_contents": "At Wed, 09 Sep 2020 14:40:37 +0900 (JST), Kyotaro Horiguchi <horikyota.ntt@gmail.com> wrote in \n> Sure. relNode is filled with zeros so RelationInitPhysicalAddr() works\n> correctly for RelationBuildDesc().\n> \n> Both changes look good to me.\n\nThank you for committing this!\n\nregards.\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Thu, 10 Sep 2020 18:58:59 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: v13: CLUSTER segv with wal_level=minimal and parallel index\n creation" } ]
[ { "msg_contents": "Hi\n\nOn these pages:\n\n https://www.postgresql.org/docs/current/fdw-callbacks.html\n https://www.postgresql.org/docs/current/tablesample-method.html\n\nwe have the phrase:\n\n \"..., which see for additional details.\"\n\nwhich strikes me as a bit odd. Suggested phrasing:\n\n \"...; see this file for additional details.\"\n\nRegards\n\nIan Barwick\n\n-- \nIan Barwick https://www.2ndQuadrant.com/\n PostgreSQL Development, 24x7 Support, Training & Services", "msg_date": "Mon, 7 Sep 2020 13:33:56 +0900", "msg_from": "Ian Barwick <ian.barwick@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "[doc] minor wording improvement in a couple of places" }, { "msg_contents": "On Mon, Sep 7, 2020 at 6:34 AM Ian Barwick <ian.barwick@2ndquadrant.com>\nwrote:\n\n> Hi\n>\n> On these pages:\n>\n> https://www.postgresql.org/docs/current/fdw-callbacks.html\n> https://www.postgresql.org/docs/current/tablesample-method.html\n>\n> we have the phrase:\n>\n> \"..., which see for additional details.\"\n>\n> which strikes me as a bit odd. Suggested phrasing:\n>\n> \"...; see this file for additional details.\"\n>\n>\nI agree this sounds very weird. However, this phrasing is also fairly\ncommon in comments around the code.\n\nI was first guessing that this came out of one of us non-english native\nspeakers, but AFAICT it's a mix of authors and definitely including those\nnatively speaking the language.\n\nI would still suggest that we change it, because it does sound odd to me as\nwell, but I'll defer a bit and see if others might think we should keep it.\n\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 7, 2020 at 6:34 AM Ian Barwick <ian.barwick@2ndquadrant.com> wrote:Hi\n\nOn these pages:\n\n   https://www.postgresql.org/docs/current/fdw-callbacks.html\n   https://www.postgresql.org/docs/current/tablesample-method.html\n\nwe have the phrase:\n\n   \"..., which see for additional details.\"\n\nwhich strikes me as a bit odd. Suggested phrasing:\n\n   \"...; see this file for additional details.\"I agree this sounds very weird. However, this phrasing is also fairly common in comments around the code.I was first guessing that this came out of one of us non-english native speakers, but AFAICT it's a mix of authors and definitely including those natively speaking the language. I would still suggest that we change it, because it does sound odd to me as well, but I'll defer a bit and see if others might think we should keep it. --  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Mon, 7 Sep 2020 12:30:27 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: [doc] minor wording improvement in a couple of places" }, { "msg_contents": "On Mon, Sep 7, 2020 at 6:30 AM Magnus Hagander <magnus@hagander.net> wrote:\n>\n> On Mon, Sep 7, 2020 at 6:34 AM Ian Barwick <ian.barwick@2ndquadrant.com> wrote:\n>> \"..., which see for additional details.\"\n>>\n>> which strikes me as a bit odd. Suggested phrasing:\n>>\n>> \"...; see this file for additional details.\"\n>>\n>\n> I agree this sounds very weird. However, this phrasing is also fairly common in comments around the code.\n\nSeems to be a literal translation of Latin \"quod vide\" (q.v.), so\nintentional, just sounds a bit old fashioned. I'd vote to keep it.\n\n-- \nJohn Naylor https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 7 Sep 2020 11:16:28 -0400", "msg_from": "John Naylor <john.naylor@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: [doc] minor wording improvement in a couple of places" } ]
[ { "msg_contents": "Hi,\n\nI observed that, in logical replication when a subscriber is missing\nsome columns, it currently emits an error message that says \"some\"\ncolumns are missing(see logicalrep_rel_open()), but it doesn't specify\nwhat the missing column names are. The comment there also says that\nfinding the missing column names is a todo item(/* TODO, detail\nmessage with names of missing columns */).\n\nI propose a patch to find the missing columns on the subscriber\nrelation using the publisher relation columns and show them in the\nerror message which can make the error more informative to the user.\n\nHere's a snapshot how the error looks with the patch:\n2020-09-04 01:00:36.721 PDT [843128] ERROR: logical replication\ntarget relation \"public.test_1\" is missing \"b1, d1\" replicated columns\n2020-09-04 01:00:46.784 PDT [843132] ERROR: logical replication\ntarget relation \"public.test_1\" is missing \"b1\" replicated columns\n2020-09-06 21:24:53.645 PDT [902945] ERROR: logical replication\ntarget relation \"public.test_1\" is missing \"a1, c1, d1, b1\" replicated\ncolumns\n\nThoughts?\n\nWith Regards,\nBharath Rupireddy.\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Mon, 7 Sep 2020 16:30:59 +0530", "msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>", "msg_from_op": true, "msg_subject": "Logical Replication - detail message with names of missing columns" }, { "msg_contents": "Thank you for working on this.\n\nAt Mon, 7 Sep 2020 16:30:59 +0530, Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com> wrote in \n> Hi,\n> \n> I observed that, in logical replication when a subscriber is missing\n> some columns, it currently emits an error message that says \"some\"\n> columns are missing(see logicalrep_rel_open()), but it doesn't specify\n> what the missing column names are. The comment there also says that\n> finding the missing column names is a todo item(/* TODO, detail\n> message with names of missing columns */).\n> \n> I propose a patch to find the missing columns on the subscriber\n> relation using the publisher relation columns and show them in the\n> error message which can make the error more informative to the user.\n\n+1 for objective. However, that can be done simpler way that doesn't\nneed additional loops by using bitmapset to hold missing remote\nattribute numbers. This also make the variable \"found\" useless.\n\n> Here's a snapshot how the error looks with the patch:\n> 2020-09-04 01:00:36.721 PDT [843128] ERROR: logical replication\n> target relation \"public.test_1\" is missing \"b1, d1\" replicated columns\n> 2020-09-04 01:00:46.784 PDT [843132] ERROR: logical replication\n> target relation \"public.test_1\" is missing \"b1\" replicated columns\n> 2020-09-06 21:24:53.645 PDT [902945] ERROR: logical replication\n> target relation \"public.test_1\" is missing \"a1, c1, d1, b1\" replicated\n> columns\n> \n> Thoughts?\n\nFWIW, I would prefer that the message be like\n\n logical replication target relation \"public.test_1\" is missing\n replicated columns: \"a1\", \"c1\"\n\nI'm not sure we need to have separate messages for singlar and plural.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Tue, 08 Sep 2020 10:20:34 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "On Tue, Sep 8, 2020 at 6:50 AM Kyotaro Horiguchi\n<horikyota.ntt@gmail.com> wrote:\n>\n> +1 for objective. However, that can be done simpler way that doesn't\n> need additional loops by using bitmapset to hold missing remote\n> attribute numbers. This also make the variable \"found\" useless.\n>\n\nThanks. I will look into it and post a v2 patch soon.\n\n>\n> > Here's a snapshot how the error looks with the patch:\n> > 2020-09-04 01:00:36.721 PDT [843128] ERROR: logical replication\n> > target relation \"public.test_1\" is missing \"b1, d1\" replicated columns\n> > 2020-09-04 01:00:46.784 PDT [843132] ERROR: logical replication\n> > target relation \"public.test_1\" is missing \"b1\" replicated columns\n> > 2020-09-06 21:24:53.645 PDT [902945] ERROR: logical replication\n> > target relation \"public.test_1\" is missing \"a1, c1, d1, b1\" replicated\n> > columns\n> >\n> > Thoughts?\n>\n> FWIW, I would prefer that the message be like\n>\n> logical replication target relation \"public.test_1\" is missing\n> replicated columns: \"a1\", \"c1\"\n>\n\nThis looks fine, I will change that.\n\n>\n> I'm not sure we need to have separate messages for singular and plural.\n>\n\nI don't think we need to have separate messages. To keep it simple,\nlet's have plural form.\n\nWith Regards,\nBharath Rupireddy.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 8 Sep 2020 09:16:31 +0530", "msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "Thanks for the comments, v2 patch is attached.\n\n>\n> On Tue, Sep 8, 2020 at 6:50 AM Kyotaro Horiguchi\n> <horikyota.ntt@gmail.com> wrote:\n> >\n> > +1 for objective. However, that can be done simpler way that doesn't\n> > need additional loops by using bitmapset to hold missing remote\n> > attribute numbers. This also make the variable \"found\" useless.\n> >\n>\n> Thanks. I will look into it and post a v2 patch soon.\n>\n\nChanged.\n\n> >\n> > FWIW, I would prefer that the message be like\n> >\n> > logical replication target relation \"public.test_1\" is missing\n> > replicated columns: \"a1\", \"c1\"\n> >\n>\n> This looks fine, I will change that.\n>\n\nChanged. Now the error looks like as shown below:\n\nERROR: logical replication target relation \"public.test_tbl1\" is\nmissing replicated columns:\"d1\"\nERROR: logical replication target relation \"public.test_tbl1\" is\nmissing replicated columns:\"c1\",\"d1\"\nERROR: logical replication target relation \"public.test_tbl1\" is\nmissing replicated columns:\"a1\",\"c1\",\"d1\"\nERROR: logical replication target relation \"public.test_tbl1\" is\nmissing replicated columns:\"a1\",\"b1\",\"c1\",\"d1\"\nERROR: logical replication target relation \"public.test_tbl1\" is\nmissing replicated columns:\"a1\",\"b1\",\"c1\",\"d1\",\"e1\"\n\n\n\nWith Regards,\nBharath Rupireddy.\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Tue, 8 Sep 2020 19:53:24 +0530", "msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "On 2020-Sep-08, Bharath Rupireddy wrote:\n\n> +\t/* Find the remote attributes that are missing in the local relation. */\n> +\tfor (i = 0; i < remoterel->natts; i++)\n> +\t{\n> +\t\tif (!bms_is_member(i, localattnums))\n> +\t\t{\n> +\t\t\tif (missingatts->len == 0)\n> +\t\t\t{\n> +\t\t\t\tappendStringInfoChar(missingatts, '\"');\n> +\t\t\t\tappendStringInfoString(missingatts, remoterel->attnames[i]);\n> +\t\t\t}\n> +\t\t\telse if (missingatts->len > 0)\n> +\t\t\t{\n> +\t\t\t\tappendStringInfoChar(missingatts, ',');\n> +\t\t\t\tappendStringInfoChar(missingatts, '\"');\n> +\t\t\t\tappendStringInfo(missingatts, \"%s\", remoterel->attnames[i]);\n> +\t\t\t}\n> +\n> +\t\t\tappendStringInfoChar(missingatts, '\"');\n> +\t\t}\n\nThis looks a bit fiddly. Would it be less cumbersome to use\nquote_identifier here instead?\n\n\n> \t\t\tereport(ERROR,\n> \t\t\t\t\t(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n> \t\t\t\t\t errmsg(\"logical replication target relation \\\"%s.%s\\\" is missing \"\n> -\t\t\t\t\t\t\t\"some replicated columns\",\n> -\t\t\t\t\t\t\tremoterel->nspname, remoterel->relname)));\n> +\t\t\t\t\t\t\t\"replicated columns:%s\",\n> +\t\t\t\t\t\t\tremoterel->nspname, remoterel->relname,\n> +\t\t\t\t\t\t\tmissingatts.data)));\n\nPlease do use errmsg_plural -- have the new function return the number\nof missing columns. Should be pretty straightforward.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 8 Sep 2020 11:49:19 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "Thanks for the comments. Attaching the v3 patch.\n\nOn Tue, Sep 8, 2020 at 8:19 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n>\n> This looks a bit fiddly. Would it be less cumbersome to use\n> quote_identifier here instead?\n>\n\nChanged. quote_identifier() adds quotes wherever necessary.\n\n>\n> Please do use errmsg_plural -- have the new function return the number\n> of missing columns. Should be pretty straightforward.\n>\n\nChanged. Now the error message looks as below:\n\nCREATE TABLE test_tbl1(a1 int, b1 text, c1 int, d1 real, e1 int);\nERROR: logical replication target relation \"public.test_tbl1\" is\nmissing replicated column:c1\nERROR: logical replication target relation \"public.test_tbl1\" is\nmissing replicated columns:b1,c1\nERROR: logical replication target relation \"public.test_tbl1\" is\nmissing replicated columns:b1,c1,e1\n\nCREATE TABLE test_tbl1(\"!A1\" int, \"%b1\" text, \"@C1\" int, d1 real, E1 int);\nERROR: logical replication target relation \"public.test_tbl1\" is\nmissing replicated column:\"@C1\"\nERROR: logical replication target relation \"public.test_tbl1\" is\nmissing replicated columns:\"@C1\",d1\nERROR: logical replication target relation \"public.test_tbl1\" is\nmissing replicated columns:\"!A1\",\"@C1\",d1\nERROR: logical replication target relation \"public.test_tbl1\" is\nmissing replicated columns:\"!A1\",\"@C1\",d1,e1\nERROR: logical replication target relation \"public.test_tbl1\" is\nmissing replicated columns:\"!A1\",\"%b1\",\"@C1\",d1,e1\n\nWith Regards,\nBharath Rupireddy.\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Tue, 8 Sep 2020 22:36:17 +0530", "msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "Added this to the commitfest - https://commitfest.postgresql.org/30/2727/\n\nWith Regards,\nBharath Rupireddy.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 10 Sep 2020 18:23:07 +0530", "msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "Thanks for the revised version.\n\nAt Tue, 8 Sep 2020 22:36:17 +0530, Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com> wrote in \n> Thanks for the comments. Attaching the v3 patch.\n> \n> On Tue, Sep 8, 2020 at 8:19 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n> >\n> > This looks a bit fiddly. Would it be less cumbersome to use\n> > quote_identifier here instead?\n> >\n> \n> Changed. quote_identifier() adds quotes wherever necessary.\n> \n> >\n> > Please do use errmsg_plural -- have the new function return the number\n> > of missing columns. Should be pretty straightforward.\n> >\n> \n> Changed. Now the error message looks as below:\n\n^^;\n\nI don't think the logicalrep_find_missing_attrs worth a separate\nfunction. The detection code would be short enough to be embedded in\nthe checking loop in logicalrep_rel_open. Note that remoterel doesn't\nhave missing columns since they are already removed when it is\nconstructed. See fetch_remote_table_info and\nlogicalrep_rel_att_by_name is relying on that fact. As the result\nthis code could be reduced to something like the following.\n\n+ /* remoterel doesn't contain dropped attributes, see .... */\n- found = 0;\n+ missing_attr = bms_add_range(NULL, 0, remoterel->natts - 1);\n for (i = 0; i < desc->natts; i++)\n if (attnum >= 0)\n- found++;\n+ missing_attrs = bms_del_member(missing_attrs, attnum);\n- if (found < remoterel->natts)\n+ if (!bms_is_empty(missing_attrs))\n+ {\n+ while ((i = bms_first_memeber(missing_attrs)) >= 0)\n+ {\n+ if (not_first) appendStringInfo(<delimter>);\n+ appendStringInfo(str, remoterel->attnames[i])\n+ }\n- erreport(\"some attrs missing\");\n+ ereport(ERROR, <blah blah>);\n+ }\n\n> ERROR: logical replication target relation \"public.test_tbl1\" is\n> missing replicated columns:b1,c1,e1\n\nI think we always double-quote identifiers in error messages. For\nexample:\n\n./catalog/index.c\u0000254: errmsg(\"primary key column \\\"%s\\\" is not marked NOT NULL\",\n./catalog/heap.c\u0000614: errmsg(\"column \\\"%s\\\" has pseudo-type %s\",\n./catalog/heap.c\u0000706: errmsg(\"no collation was derived for column \\\"%s\\\" with collatable type %s\",\n\nAnd we need a space after the semicolon and commas in the message\nstring.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 11 Sep 2020 10:14:18 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "Thanks for the review comments. Attaching v4 patch.\n\nOn Fri, Sep 11, 2020 at 6:44 AM Kyotaro Horiguchi <horikyota.ntt@gmail.com>\nwrote:\n>\n> + /* remoterel doesn't contain dropped attributes, see .... */\n> - found = 0;\n> + missing_attr = bms_add_range(NULL, 0, remoterel->natts - 1);\n> for (i = 0; i < desc->natts; i++)\n> if (attnum >= 0)\n> - found++;\n> + missing_attrs = bms_del_member(missing_attrs, attnum);\n> - if (found < remoterel->natts)\n> + if (!bms_is_empty(missing_attrs))\n> + {\n> + while ((i = bms_first_memeber(missing_attrs)) >= 0)\n> + {\n> + if (not_first) appendStringInfo(<delimter>);\n> + appendStringInfo(str, remoterel->attnames[i])\n> + }\n> - erreport(\"some attrs missing\");\n> + ereport(ERROR, <blah blah>);\n> + }\n>\n\n+1. Yes, the remoterel doesn't contain dropped attributes.\n\n>\n> > ERROR: logical replication target relation \"public.test_tbl1\" is\n> > missing replicated columns:b1,c1,e1\n>\n> I think we always double-quote identifiers in error messages. For\n> example:\n>\n> ./catalog/index.c 254: errmsg(\"primary key column \\\"%s\\\" is not marked\nNOT NULL\",\n> ./catalog/heap.c 614: errmsg(\"column \\\"%s\\\" has pseudo-type %s\",\n> ./catalog/heap.c 706: errmsg(\"no collation was derived for column \\\"%s\\\"\nwith collatable type %s\",\n>\n\nDouble-quoting identifiers such as database object names helps in clearly\nidentifying them from the normal error message text. Seems like everywhere\nwe double-quote columns in the error messages. One exception I found\nthough, for relation names(there may be more places where we are not\ndouble-quoting) is in errmsg(\"could not open parent table of index %s\",\nRelationGetRelationName(indrel).\n\nHow about quoting all the individual columns? Looks like quote_identifier()\ndoesn't serve our purpose here as it selectively quotes or quotes all\nidentifiers only in case quote_all_identifiers config variable is set.\n\nCREATE TABLE t1(a1 int, b1 text, c1 real, d1 int, e1 int);\n2020-09-10 23:08:26.737 PDT [217404] ERROR: logical replication target\nrelation \"public.t1\" is missing replicated column: \"c1\"\n2020-09-10 23:08:31.768 PDT [217406] ERROR: logical replication target\nrelation \"public.t1\" is missing replicated columns: \"c1\", \"d1\"\n2020-09-10 23:08:51.898 PDT [217417] ERROR: logical replication target\nrelation \"public.t1\" is missing replicated columns: \"c1\", \"d1\", \"e1\"\n\nCREATE TABLE t1(\"!A1\" int, \"%b1\" text, \"@C1\" int, d1 real, E1 int);\n2020-09-10 23:12:29.768 PDT [217501] ERROR: logical replication target\nrelation \"public.t1\" is missing replicated column: \"!A1\"\n2020-09-10 23:12:56.640 PDT [217515] ERROR: logical replication target\nrelation \"public.t1\" is missing replicated columns: \"!A1\", \"@C1\"\n2020-09-10 23:13:31.848 PDT [217533] ERROR: logical replication target\nrelation \"public.t1\" is missing replicated columns: \"!A1\", \"@C1\", \"d1\"\n\n>\n> And we need a space after the semicolon and commas in the message\n> string.\n>\n\nChanged.\n\nWith Regards,\nBharath Rupireddy.\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Fri, 11 Sep 2020 18:12:41 +0530", "msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com> writes:\n>> I think we always double-quote identifiers in error messages. For\n>> example:\n>> ./catalog/heap.c 706: errmsg(\"no collation was derived for column \\\"%s\\\"\n>> with collatable type %s\",\n\nRight. Anything in this patch that is not doing that needs to be fixed.\n(As this example shows, type names are exempt from the rule.)\n\n> How about quoting all the individual columns? Looks like quote_identifier()\n> doesn't serve our purpose here as it selectively quotes or quotes all\n> identifiers only in case quote_all_identifiers config variable is set.\n\nNO. The convention is to write \\\"...\\\" in the translatable message.\nNot all languages use double quote symbols for this purpose, so that\nway lets translators replace them with something else.\n\nYeah, this means that messages containing names that contain double\nquotes might be a bit ambiguous. We live with it.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 11 Sep 2020 10:10:32 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "On 2020-Sep-11, Tom Lane wrote:\n\n> > How about quoting all the individual columns? Looks like quote_identifier()\n> > doesn't serve our purpose here as it selectively quotes or quotes all\n> > identifiers only in case quote_all_identifiers config variable is set.\n> \n> NO. The convention is to write \\\"...\\\" in the translatable message.\n> Not all languages use double quote symbols for this purpose, so that\n> way lets translators replace them with something else.\n> \n> Yeah, this means that messages containing names that contain double\n> quotes might be a bit ambiguous. We live with it.\n\nThere is a problem here though, which is that the quoted strings in\nquestion are part of a list of columns. There's no way to keep that\nlist as a translatable string, so that approach doesn't work here.\nWhat appears in the translatable string is:\n\nlogical replication target relation \"%s\" is missing replicated columns: %s\n\nOr in the singular case:\nlogical replication target relation \"%s\" is missing replicated columns: %s\n\nwhere the second %s is the list of columns.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 11 Sep 2020 11:35:46 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> On 2020-Sep-11, Tom Lane wrote:\n>> NO. The convention is to write \\\"...\\\" in the translatable message.\n\n> There is a problem here though, which is that the quoted strings in\n> question are part of a list of columns. There's no way to keep that\n> list as a translatable string, so that approach doesn't work here.\n> What appears in the translatable string is:\n\n> logical replication target relation \"%s\" is missing replicated columns: %s\n\nCheck, but you could imagine that the column-list string is constructed\nwith code along the lines of\n\n\tif (first)\n\t appendStringInfo(buf, _(\"\\\"%s\\\"\"), colname);\n\telse\n\t appendStringInfo(buf, _(\", \\\"%s\\\"\"), colname);\n\nthus allowing a translator to replace the quote marks. Might not be\nworth the trouble. In any case, the point here is that we're not\ntrying to construct valid SQL so quote_identifier is not the right\ntool for the job.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 11 Sep 2020 10:52:23 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "On 2020-Sep-11, Tom Lane wrote:\n\n> Check, but you could imagine that the column-list string is constructed\n> with code along the lines of\n> \n> \tif (first)\n> \t appendStringInfo(buf, _(\"\\\"%s\\\"\"), colname);\n> \telse\n> \t appendStringInfo(buf, _(\", \\\"%s\\\"\"), colname);\n> thus allowing a translator to replace the quote marks.\n\nThis works OK for my language at least. I couldn't find any guidance on\nwhether there's a problem doing things this way for RTL languages etc,\nbut +1 for doing it this way.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 11 Sep 2020 12:35:43 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> This works OK for my language at least. I couldn't find any guidance on\n> whether there's a problem doing things this way for RTL languages etc,\n> but +1 for doing it this way.\n\nHmm ... fortunately, there's not any large semantic significance to the\norder in which the columns are mentioned here. Maybe an RTL speaker\nwould read the column names in the opposite order than we do, but I\ndon't think it's a problem.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 11 Sep 2020 11:41:59 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "On Fri, Sep 11, 2020 at 9:05 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n>\n> On 2020-Sep-11, Tom Lane wrote:\n>\n> > Check, but you could imagine that the column-list string is constructed\n> > with code along the lines of\n> >\n> > if (first)\n> > appendStringInfo(buf, _(\"\\\"%s\\\"\"), colname);\n> > else\n> > appendStringInfo(buf, _(\", \\\"%s\\\"\"), colname);\n> > thus allowing a translator to replace the quote marks.\n>\n> This works OK for my language at least. I couldn't find any guidance on\n> whether there's a problem doing things this way for RTL languages etc,\n> but +1 for doing it this way.\n>\n\nThanks for the comments. I changed the patch to use the string\npreparation in below fashion. Attaching the v5 patch. Please let me\nknow if there are any further inputs.\n\n+ if (missingattcnt == 1)\n+ appendStringInfo(&missingattsbuf, _(\"\\\"%s\\\"\"),\n+ remoterel->attnames[i]);\n+ else\n+ appendStringInfo(&missingattsbuf, _(\", \\\"%s\\\"\"),\n+ remoterel->attnames[i]);\n\nWith Regards,\nBharath Rupireddy.\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Sat, 12 Sep 2020 19:15:24 +0530", "msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "Attaching v6 patch, rebased because of a recent commit\n3d65b0593c5578014f62e09d4008006f1783f64d. Please consider this for\nfurther review.\n\nWith Regards,\nBharath Rupireddy.\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Wed, 16 Sep 2020 21:58:28 +0530", "msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "On Wed, Sep 16, 2020 at 9:58 PM Bharath Rupireddy\n<bharath.rupireddyforpostgres@gmail.com> wrote:\n>\n> Attaching v6 patch, rebased because of a recent commit\n> 3d65b0593c5578014f62e09d4008006f1783f64d. Please consider this for\n> further review.\n>\n\nFew comments:\n==============\n1.\n+ /* Report error with names of the missing localrel column(s). */\n+ if (!bms_is_empty(missingatts))\n+ {\n+ StringInfoData missingattsbuf;\n+ int missingattcnt = 0;\n+\n+ initStringInfo(&missingattsbuf);\n+ while ((i = bms_first_member(missingatts)) >= 0)\n+ {\n+ missingattcnt++;\n+ if (missingattcnt == 1)\n+ appendStringInfo(&missingattsbuf, _(\"\\\"%s\\\"\"),\n+ remoterel->attnames[i]);\n+ else\n+ appendStringInfo(&missingattsbuf, _(\", \\\"%s\\\"\"),\n+ remoterel->attnames[i]);\n+ }\n+\n+ bms_free(missingatts);\n ereport(ERROR,\n (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n- errmsg(\"logical replication target relation \\\"%s.%s\\\" is missing \"\n- \"some replicated columns\",\n- remoterel->nspname, remoterel->relname)));\n+ errmsg_plural(\"logical replication target relation \\\"%s.%s\\\" is missing \"\n+ \"replicated column: %s\",\n+ \"logical replication target relation \\\"%s.%s\\\" is missing \"\n+ \"replicated columns: %s\",\n+ missingattcnt,\n+ remoterel->nspname,\n+ remoterel->relname,\n+ missingattsbuf.data)));\n+ }\n\nI think it is better to move the above code in a separate function\n(say logicalrep_report_missing_attrs or something like that).\n\n2. I think we always need to call bms_free(missingatts) because it is\npossible that there is no missing attribute and in that case, we won't\nfree the memory allocated in bms_add_range.\n\n3. The patch doesn't seem to be freeing the memory allocated for missingattsbuf.\n\n4.\n ereport(ERROR,\n (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n- errmsg(\"logical replication target relation \\\"%s.%s\\\" is missing \"\n- \"some replicated columns\",\n- remoterel->nspname, remoterel->relname)));\n+ errmsg_plural(\"logical replication target relation \\\"%s.%s\\\" is missing \"\n+ \"replicated column: %s\",\n+ \"logical replication target relation \\\"%s.%s\\\" is missing \"\n+ \"replicated columns: %s\",\n+ missingattcnt,\n+ remoterel->nspname,\n+ remoterel->relname,\n+ missingattsbuf.data)));\n\n From the second line onwards, the message lines are not aligned in\nerrmsg_plural.\n\n5. Also, in the above message, keep the error string in a single line.\nFor ex. see one of the existing messages:\nerrmsg_plural(\"WAL segment size must be a power of two between 1 MB\nand 1 GB, but the control file specifies %d byte\", .. I think it will\nbe easy to read that way. I know this is not exactly related to your\npatch but improving it while changing this message seems fine.\n\n6. I think we should add one test case for this in the existing\nregression test (src/test/subscription/t/008_diff_schema).\n\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Mon, 5 Oct 2020 09:39:51 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "Thanks Amit for the review comments. I will post an updated patch soon.\n\nOn Mon, Oct 5, 2020 at 9:39 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> 6. I think we should add one test case for this in the existing\n> regression test (src/test/subscription/t/008_diff_schema).\n>\n\nThis patch logs the missing column names message in subscriber server\nlogs. Is there a way to see the logs in these tests and use that as\nexpected result for the test case?\n\nWith Regards,\nBharath Rupireddy.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 5 Oct 2020 19:59:55 +0530", "msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "On Mon, Oct 5, 2020 at 8:00 PM Bharath Rupireddy\n<bharath.rupireddyforpostgres@gmail.com> wrote:\n>\n> Thanks Amit for the review comments. I will post an updated patch soon.\n>\n> On Mon, Oct 5, 2020 at 9:39 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> > 6. I think we should add one test case for this in the existing\n> > regression test (src/test/subscription/t/008_diff_schema).\n> >\n>\n> This patch logs the missing column names message in subscriber server\n> logs. Is there a way to see the logs in these tests and use that as\n> expected result for the test case?\n>\n\nI don't think there is any direct way to achieve that. What we can do\nis to check that the data is not replicated in such a case but I don't\nthink it is worth to add a test for that behavior. So, I think we can\nskip adding a test for this unless someone else has a better idea to\ndo the same.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 6 Oct 2020 09:15:37 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "Thanks Amit for the review comments.\n\nOn Mon, Oct 5, 2020 at 9:39 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> Few comments:\n> ==============\n> 1.\n> + /* Report error with names of the missing localrel column(s). */\n> + if (!bms_is_empty(missingatts))\n> + {\n> + StringInfoData missingattsbuf;\n> + int missingattcnt = 0;\n> + remoterel->nspname,\n> + remoterel->relname,\n> + missingattsbuf.data)));\n> + }\n>\n> I think it is better to move the above code in a separate function\n> (say logicalrep_report_missing_attrs or something like that).\n>\n\nAdded a new function logicalrep_report_missing_attrs().\n\n>\n> 2. I think we always need to call bms_free(missingatts) because it is\n> possible that there is no missing attribute and in that case, we won't\n> free the memory allocated in bms_add_range.\n>\n\nDone. Yes we palloc memory for missingatts bitmap irrespective of missing\nattributes. Added bms_free() out of if(!bms_is_empty(missingatts)) as well.\nI also kept bms_free() before ereport(ERROR,..) to free up before throwing\nthe error. In anycase, only one bms_free() would get hit.\n\nif (!bms_is_empty(missingatts))\n{\nStringInfoData missingattsbuf;\nint missingattcnt = 0;\n\nbms_free(missingatts);\nereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\nerrmsg_plural(\"logical replication target relation \\\"%s.%s\\\" is missing\nreplicated column: %s\",\n \"logical replication target relation \\\"%s.%s\\\" is missing replicated\ncolumns: %s\",\n missingattcnt,\n remoterel->nspname,\n remoterel->relname,\n missingattsbuf.data)));\n}\nbms_free(missingatts);\n\n>\n> 3. The patch doesn't seem to be freeing the memory allocated for\nmissingattsbuf.\n>\n\nI don't think we need to do that. We are passing missingattsbuf.data to\nereport and we are safe without freeing up missingattsbuf(we don't reach\nthe code after ereprot(ERROR,...)as the table sync worker anyways goes away\nafter throwing missing attributes error( if (sigsetjmp(local_sigjmp_buf, 1)\n!= 0) in StartBackgroundWorker and then proc_exit(1)). Each time a new\ntable sync bg worker is spawned.\n\n2020-10-06 10:18:27.063 IST [1599963] ERROR: logical replication target\nrelation \"public.t1\" is missing replicated column: \"@C1\"\n2020-10-06 10:18:47.179 IST [1600134] ERROR: logical replication target\nrelation \"public.t1\" is missing replicated column: \"@C1\"\n2020-10-06 10:18:57.234 IST [1600214] ERROR: logical replication target\nrelation \"public.t1\" is missing replicated column: \"@C1\"\n\n2020-10-06 10:19:27.415 IST [1600458] ERROR: logical replication target\nrelation \"public.t1\" is missing replicated columns: \"%b1\", \"@C1\"\n2020-10-06 10:19:42.506 IST [1600588] ERROR: logical replication target\nrelation \"public.t1\" is missing replicated columns: \"%b1\", \"@C1\"\n2020-10-06 10:19:52.565 IST [1600669] ERROR: logical replication target\nrelation \"public.t1\" is missing replicated columns: \"%b1\", \"@C1\"\n\n>\n> 4.\n> ereport(ERROR,\n> (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n> - errmsg(\"logical replication target relation \\\"%s.%s\\\" is missing \"\n>\n> From the second line onwards, the message lines are not aligned in\n> errmsg_plural.\n>\n\nDone.\n\n>\n> 5. Also, in the above message, keep the error string in a single line.\n> For ex. see one of the existing messages:\n> errmsg_plural(\"WAL segment size must be a power of two between 1 MB\n> and 1 GB, but the control file specifies %d byte\", .. I think it will\n> be easy to read that way. I know this is not exactly related to your\n> patch but improving it while changing this message seems fine.\n>\n\nDone.\n\nAttaching v7 patch please consider it for further review.\n\nWith Regards,\nBharath Rupireddy.\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Tue, 6 Oct 2020 12:14:22 +0530", "msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "On Tue, Oct 6, 2020 at 12:14 PM Bharath Rupireddy\n<bharath.rupireddyforpostgres@gmail.com> wrote:\n>\n> On Mon, Oct 5, 2020 at 9:39 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> >\n> > 3. The patch doesn't seem to be freeing the memory allocated for missingattsbuf.\n> >\n>\n> I don't think we need to do that. We are passing missingattsbuf.data to ereport and we are safe without freeing up missingattsbuf(we don't reach the code after ereprot(ERROR,...)as the table sync worker anyways goes away after throwing missing attributes error( if (sigsetjmp(local_sigjmp_buf, 1) != 0) in StartBackgroundWorker and then proc_exit(1)). Each time a new table sync bg worker is spawned.\n>\n\nOkay, by that logic, we don't even need to free memory for missingatts.\n\nI have made a few changes, (a) moved free of missingatts in the caller\nwhere we are allocating it. (b) added/edited/removed comments, (c) ran\npgindent.\n\nShall we backpatch this? I don't see any particular need to backpatch\nthis as this is a minor error message improvement and nobody has\nreported any problem due to this. What do you think?\n\n-- \nWith Regards,\nAmit Kapila.", "msg_date": "Tue, 6 Oct 2020 17:24:48 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "On Tue, Oct 6, 2020 at 5:24 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Tue, Oct 6, 2020 at 12:14 PM Bharath Rupireddy\n> <bharath.rupireddyforpostgres@gmail.com> wrote:\n> >\n> > On Mon, Oct 5, 2020 at 9:39 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > >\n> > >\n> > > 3. The patch doesn't seem to be freeing the memory allocated for missingattsbuf.\n> > >\n> >\n> > I don't think we need to do that. We are passing missingattsbuf.data to ereport and we are safe without freeing up missingattsbuf(we don't reach the code after ereprot(ERROR,...)as the table sync worker anyways goes away after throwing missing attributes error( if (sigsetjmp(local_sigjmp_buf, 1) != 0) in StartBackgroundWorker and then proc_exit(1)). Each time a new table sync bg worker is spawned.\n> >\n>\n> Okay, by that logic, we don't even need to free memory for missingatts.\n>\n> I have made a few changes, (a) moved free of missingatts in the caller\n> where we are allocating it. (b) added/edited/removed comments, (c) ran\n> pgindent.\n>\n\nThanks Amit. v8 patch looks good to me.\n\n>\n> Shall we backpatch this? I don't see any particular need to backpatch\n> this as this is a minor error message improvement and nobody has\n> reported any problem due to this. What do you think?\n>\n\nIMO, no backpatch is required as this is not a bug or something\nreported by anyone.\n\nWith Regards,\nBharath Rupireddy.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 6 Oct 2020 18:36:34 +0530", "msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" }, { "msg_contents": "On 2020-Oct-06, Amit Kapila wrote:\n\n> I have made a few changes, (a) moved free of missingatts in the caller\n> where we are allocating it. (b) added/edited/removed comments, (c) ran\n> pgindent.\n\nThis is committed as f07707099c17.\n\nThanks\n\n\n", "msg_date": "Thu, 15 Oct 2020 12:17:50 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: Logical Replication - detail message with names of missing\n columns" } ]
[ { "msg_contents": "Hi Hackers,\n\nI observed that we have inaccurate comment in\nenforce_generic_type_consistency.\n\n if (!OidIsValid(elem_typeid))\n {\n if (allow_poly)\n {\n elem_typeid = ANYELEMENTOID;\n array_typeid = ANYARRAYOID;\n range_typeid = ANYRANGEOID;\n }\n else\n {\n /*\n * Only way to get here is if all the\npolymorphic args have\n * UNKNOWN inputs\n */\n *ereport(ERROR, *\n ...............\n }\n........\n}\nWe reach the error condition even if there is any \"anycompatible\" parameter\nis present (and that is of some known type say int32).\nI think developer intend to report error if \"we have all the family-1\npolymorphic arguments as UNKNOWN\".\n\nThoughts?\n\nPlease find attached the patch to fix this typo.\n\nThanks,\nHimanshu\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Mon, 7 Sep 2020 17:33:49 +0530", "msg_from": "Himanshu Upadhyaya <upadhyaya.himanshu@gmail.com>", "msg_from_op": true, "msg_subject": "Inaccurate comment, for family-1 polymorphic UNKNOWN type arguments" }, { "msg_contents": "Himanshu Upadhyaya <upadhyaya.himanshu@gmail.com> writes:\n> I observed that we have inaccurate comment in\n> enforce_generic_type_consistency.\n\nFair point, but that's not the only old comment that's not being careful\nabout it. I applied the attached.\n\n\t\t\tregards, tom lane", "msg_date": "Mon, 07 Sep 2020 14:54:15 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Inaccurate comment,\n for family-1 polymorphic UNKNOWN type arguments" } ]
[ { "msg_contents": "Hi,\n\nhaving just spoken with Harald Armin Massa of 2ndQuadrant, he encouraged me to ask my question here. This is about publisher/subscriber replication and was originally posted in german to pgsql-de-allgemein@lists.postgresql.org.\n\nAccording to documentation, the field pg_stats_subscription.latest_end_time contains the \"Time of last write-ahead log location reported to origin WAL sender\" [1].\nThe view is built from the internal function pg_stat_get_subscription() [2, line 1097], defined in launcher.c, where we can see that the field is populated from a struct LogicalRepWorker. Write access to the relevant struct happens in worker.c from UpdateWorkerStats() but only if reply=true [3, line 1109], which in turn only happens whenever LogicalRepApplyLoop() deals with a message beginning with 'k' [3, line 1227]. This message is constructed by the publisher in walsender.c in WalSndKeepalive() [4, line 3435], where the corresponding value is always GetCurrentTimestamp().\n\nAs far as I understand, the WAL replication process has the publisher send messages with WAL slices (type 'w') and keepalive messages (type 'k'), to which the subscriber answers with a heartbeat. Other message types are not relevant here. If the documentation is correct, shouldn't latest_end_time use the creation time of the publisher's most recent WAL slice? On the other hand, wouldn't \"time of last communication from WAL sender\" be a more appropriate description of the actual behaviour? And in that case, why only consider 'k'-messages instead of 'w'-messages that contain data?\n\nEither way, I'm confused as to the meaning of pg_stats_subscription.latest_end_time. The documentation as is also lead to discussions in the office, because \"reported to ... sender\" is ambiguous as to who reports: It might mean some kind of feedback from the subscriber.\n\n\nPlease enlighten me, and please excuse the footer, which I can't turn off.\n\n[1] https://www.postgresql.org/docs/12/monitoring-stats.html#PG-STAT-SUBSCRIPTION\n[2] https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/replication/logical/launcher.c;h=186057bd9327383b7dfdc2d2dda878290caa7967;hb=5060275aa8a1ead56e0a41308d7a43049a6cbe43\n[3] https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/replication/logical/worker.c;h=790a28fc77e47c7024b8605448311aaa4325fb5b;hb=5060275aa8a1ead56e0a41308d7a43049a6cbe43\n[4] https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/replication/walsender.c;h=89fbb6fd92788fca66eeb93aaabed7f63dd940c2;hb=5060275aa8a1ead56e0a41308d7a43049a6cbe43\n\n\nIm Auftrag\nSimon Schneider\n\nStadt Köln - Die Oberbürgermeisterin\nBerufsfeuerwehr, Amt für Feuerschutz, Rettungsdienst und Bevölkerungsschutz\nBoltensternstr. 10\n50735 Köln\n\nTelefon: 0221/9748-9092\nTelefax: 0221/9748-9004\nE-Mail: simon.schneider@stadt-koeln.de\nInternet: https://www.stadt-koeln.de\n\n\n________________________________\n________________________________\n\nMonatlich aktuelle Informationen Ihrer Stadtverwaltung in unserem Newsletter! Newsletter Anmeldung<https://www.stadt-koeln.de/service/onlinedienste/newsletter-anmeldung?para=allgemein>\n\n________________________________\n________________________________\n\n[https://styleguide.bundesregierung.de/resource/blob/72496/1760346/6d7f611945ca42908c50804510c5335b/breg-vorschaubild-01-unterstuetzt-842x595px-jpg-srgb-v01-data.png]<https://www.bundesregierung.de/breg-de/themen/corona-warn-app>\n[https://www.stadt-koeln.de/images/footer_wahlhelferaufruf2020.jpg]<http://www.wahlhelfer.koeln/>\n\n\n\n", "msg_date": "Mon, 7 Sep 2020 16:48:22 +0000", "msg_from": "<Simon.Schneider@STADT-KOELN.DE>", "msg_from_op": true, "msg_subject": "Meaning of pg_stats_subscription.latest_end_time" } ]
[ { "msg_contents": "Hello hackers,\n\nCurrently, database recovery from archive is performed sequentially,\nby reading archived WAL files and applying their records to the database.\n\nOverall archive file processing is done one by one, and this might\ncreate a performance bottleneck if archived WAL files are delivered slowly,\nbecause the database server has to wait for arrival of the next\nWAL segment before applying its records.\n\nTo address this issue it is proposed to receive archived WAL files in parallel\nso that when the next WAL segment file is required for processing of redo log\nrecords it would be already available.\n\nImplementation of this approach assumes running several background processes (bgworkers)\neach of which runs a shell command specified by the parameter restore_command\nto deliver an archived WAL file. Number of running parallel processes is limited\nby the new parameter max_restore_command_workers. If this parameter has value 0\nthen WAL files delivery is performed using the original algorithm, that is in\none-by-one manner. If this parameter has value greater than 0 then the database\nserver starts several bgworker processes up to the limit specified by\nthe parameter max_restore_command_workers and passes to every process\nWAL file name to deliver. Active processes start prefetching of specified\nWAL files and store received files in the directory pg_wal/pgsql_tmp. After\nbgworker process finishes receiving a file it marks itself as a free process\nand waits for a new request to receive a next WAL file. The main process\nperforming database recovery still handles WAL files in one-by-one manner,\nbut instead of waiting for a next required WAL file's availability it checks for\nthat file in the prefetched directory. If a new file is present there,\nthe main process starts its processing.\n\nThe patch implemeting the described approach is attached to this email.\nThe patch contains a test in the file src/test/recovery/t/021_xlogrestore.pl\nAlthough the test result depends on real execution time and hardly could be\napproved for including to the repository it was added in order to show\na positive effect from applying the new algorithm. In my environment restoring\nfrom archive with parallel prefetching is twice as faster than in original\nmode.\n\nRegards,\nDmitry.", "msg_date": "Tue, 8 Sep 2020 11:51:48 +0700", "msg_from": "Dmitry Shulga <d.shulga@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Reduce the time required for a database recovery from archive." }, { "msg_contents": "út 8. 9. 2020 v 6:51 odesílatel Dmitry Shulga <d.shulga@postgrespro.ru>\nnapsal:\n\n> Hello hackers,\n>\n> Currently, database recovery from archive is performed sequentially,\n> by reading archived WAL files and applying their records to the database.\n>\n> Overall archive file processing is done one by one, and this might\n> create a performance bottleneck if archived WAL files are delivered slowly,\n> because the database server has to wait for arrival of the next\n> WAL segment before applying its records.\n>\n> To address this issue it is proposed to receive archived WAL files in\n> parallel\n> so that when the next WAL segment file is required for processing of redo\n> log\n> records it would be already available.\n>\n> Implementation of this approach assumes running several background\n> processes (bgworkers)\n> each of which runs a shell command specified by the parameter\n> restore_command\n> to deliver an archived WAL file. Number of running parallel processes is\n> limited\n> by the new parameter max_restore_command_workers. If this parameter has\n> value 0\n> then WAL files delivery is performed using the original algorithm, that is\n> in\n> one-by-one manner. If this parameter has value greater than 0 then the\n> database\n> server starts several bgworker processes up to the limit specified by\n> the parameter max_restore_command_workers and passes to every process\n> WAL file name to deliver. Active processes start prefetching of specified\n> WAL files and store received files in the directory pg_wal/pgsql_tmp. After\n> bgworker process finishes receiving a file it marks itself as a free\n> process\n> and waits for a new request to receive a next WAL file. The main process\n> performing database recovery still handles WAL files in one-by-one manner,\n> but instead of waiting for a next required WAL file's availability it\n> checks for\n> that file in the prefetched directory. If a new file is present there,\n> the main process starts its processing.\n>\n> The patch implemeting the described approach is attached to this email.\n> The patch contains a test in the file src/test/recovery/t/\n> 021_xlogrestore.pl\n> Although the test result depends on real execution time and hardly could be\n> approved for including to the repository it was added in order to show\n> a positive effect from applying the new algorithm. In my environment\n> restoring\n> from archive with parallel prefetching is twice as faster than in original\n> mode.\n>\n\n+1\n\nit is interesting feature\n\nRegards\n\nPavel\n\n\n> Regards,\n> Dmitry.\n>\n>\n\nút 8. 9. 2020 v 6:51 odesílatel Dmitry Shulga <d.shulga@postgrespro.ru> napsal:Hello hackers,\n\nCurrently, database recovery from archive is performed sequentially,\nby reading archived WAL files and applying their records to the database.\n\nOverall archive file processing is done one by one, and this might\ncreate a performance bottleneck if archived WAL files are delivered slowly,\nbecause the database server has to wait for arrival of the next\nWAL segment before applying its records.\n\nTo address this issue it is proposed to receive archived WAL files in parallel\nso that when the next WAL segment file is required for processing of redo log\nrecords it would be already available.\n\nImplementation of this approach assumes running several background processes (bgworkers)\neach of which runs a shell command specified by the parameter restore_command\nto deliver an archived WAL file. Number of running parallel processes is limited\nby the new parameter max_restore_command_workers. If this parameter has value 0\nthen WAL files delivery is performed using the original algorithm, that is in\none-by-one manner. If this parameter has value greater than 0 then the database\nserver starts several bgworker processes up to the limit specified by\nthe parameter max_restore_command_workers and passes to every process\nWAL file name to deliver. Active processes start prefetching of specified\nWAL files and store received files in the directory pg_wal/pgsql_tmp. After\nbgworker process finishes receiving a file it marks itself as a free process\nand waits for a new request to receive a next WAL file. The main process\nperforming database recovery still handles WAL files in one-by-one manner,\nbut instead of waiting for a next required WAL file's availability it checks for\nthat file in the prefetched directory. If a new file is present there,\nthe main process starts its processing.\n\nThe patch implemeting the described approach is attached to this email.\nThe patch contains a test in the file src/test/recovery/t/021_xlogrestore.pl\nAlthough the test result depends on real execution time and hardly could be\napproved for including to the repository it was added in order to show\na positive effect from applying the new algorithm. In my environment restoring\nfrom archive with parallel prefetching is twice as faster than in original\nmode.+1it is interesting featureRegardsPavel\n\nRegards,\nDmitry.", "msg_date": "Tue, 8 Sep 2020 07:45:43 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Reduce the time required for a database recovery from archive." }, { "msg_contents": "Greetings,\n\n* Dmitry Shulga (d.shulga@postgrespro.ru) wrote:\n> Overall archive file processing is done one by one, and this might\n> create a performance bottleneck if archived WAL files are delivered slowly,\n> because the database server has to wait for arrival of the next\n> WAL segment before applying its records.\n> \n> To address this issue it is proposed to receive archived WAL files in parallel\n> so that when the next WAL segment file is required for processing of redo log\n> records it would be already available.\n\nYes, pgbackrest already does exactly this (if configured)- uses parallel\nprocesses to fetch the WAL and have it be available ahead of time.\n\n> Implementation of this approach assumes running several background processes (bgworkers)\n> each of which runs a shell command specified by the parameter restore_command\n> to deliver an archived WAL file. Number of running parallel processes is limited\n> by the new parameter max_restore_command_workers. If this parameter has value 0\n> then WAL files delivery is performed using the original algorithm, that is in\n> one-by-one manner. If this parameter has value greater than 0 then the database\n> server starts several bgworker processes up to the limit specified by\n> the parameter max_restore_command_workers and passes to every process\n> WAL file name to deliver. Active processes start prefetching of specified\n> WAL files and store received files in the directory pg_wal/pgsql_tmp. After\n> bgworker process finishes receiving a file it marks itself as a free process\n> and waits for a new request to receive a next WAL file. The main process\n> performing database recovery still handles WAL files in one-by-one manner,\n> but instead of waiting for a next required WAL file's availability it checks for\n> that file in the prefetched directory. If a new file is present there,\n> the main process starts its processing.\n\nI'm a bit confused about this description- surely it makes sense for the\nparallel workers to continue to loop and fetch up to some specified\nmax..? Then to monitor and to fetch more when the amount pre-fetched so\nfar drops before that level? The description above makes it sound like\nX WAL will be fetched ahead of time, and then the recovery process will\ngo through those until it runs out and then it'll have to wait for the\nnext X WAL to be fetched, which means it's still going to end up being\ndelayed even with these parallel processes, which isn't good.\n\nDoes this also properly handle timeline switches..?\n\nThanks,\n\nStephen", "msg_date": "Wed, 9 Sep 2020 10:26:55 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Reduce the time required for a database recovery from archive." }, { "msg_contents": "Hello Stephen\n\n> On 9 Sep 2020, at 21:26, Stephen Frost <sfrost@snowman.net> wrote:\n> \n> Greetings,\n> \n> * Dmitry Shulga (d.shulga@postgrespro.ru) wrote:\n>> Overall archive file processing is done one by one, and this might\n>> create a performance bottleneck if archived WAL files are delivered slowly,\n>> because the database server has to wait for arrival of the next\n>> WAL segment before applying its records.\n>> \n>> To address this issue it is proposed to receive archived WAL files in parallel\n>> so that when the next WAL segment file is required for processing of redo log\n>> records it would be already available.\n> \n> Yes, pgbackrest already does exactly this (if configured)- uses parallel\n> processes to fetch the WAL and have it be available ahead of time.\n\npgbackrest is a third-party software that should be additionally installed on customer's premises.\n\nOn the other hand, built-in support of this optimization in PostgresSQL is a good argument to add\nthis feature and provide it to customers just out of the box.\n \n> \n>> Implementation of this approach assumes running several background processes (bgworkers)\n>> each of which runs a shell command specified by the parameter restore_command\n>> to deliver an archived WAL file. Number of running parallel processes is limited\n>> by the new parameter max_restore_command_workers. If this parameter has value 0\n>> then WAL files delivery is performed using the original algorithm, that is in\n>> one-by-one manner. If this parameter has value greater than 0 then the database\n>> server starts several bgworker processes up to the limit specified by\n>> the parameter max_restore_command_workers and passes to every process\n>> WAL file name to deliver. Active processes start prefetching of specified\n>> WAL files and store received files in the directory pg_wal/pgsql_tmp. After\n>> bgworker process finishes receiving a file it marks itself as a free process\n>> and waits for a new request to receive a next WAL file. The main process\n>> performing database recovery still handles WAL files in one-by-one manner,\n>> but instead of waiting for a next required WAL file's availability it checks for\n>> that file in the prefetched directory. If a new file is present there,\n>> the main process starts its processing.\n> \n> I'm a bit confused about this description- surely it makes sense for the\nOK. The description I originally provided was probably pretty misleading so I will try to clarify it a bit.\n\nSo, as soon as a bgworker process finishes delivering a WAL file it marks itself as a free.\n\nWAL records applier working in parallel and processing the WAL files in sequential manner.\nOnce it finishes handling of the current WAL file, it checks whether it is possible to run extra bgworker processes\nto deliver WAL files which will be required a bit later. If there are free bgworker processes then applier requests \nto start downloading of one or more extra WAL files. After that applier determines a name of next WAL file to handle\nand checks whether it exist in the prefetching directory. If it does exist then applier starts handling it and\nprocessing loop is repeated. \n\n> parallel workers to continue to loop and fetch up to some specified\n> max..? Then to monitor and to fetch more when the amount pre-fetched so\n> far drops before that level? The description above makes it sound like\n> X WAL will be fetched ahead of time, and then the recovery process will\n> go through those until it runs out and then it'll have to wait for the\n> next X WAL to be fetched, which means it's still going to end up being\n> delayed even with these parallel processes, which isn't good.\n> \n\n> Does this also properly handle timeline switches..?\n> \n> Thanks,\n> \n> Stephen\n\nRegards,\nDmitry\n\n\n\n\n", "msg_date": "Mon, 19 Oct 2020 14:58:15 +0700", "msg_from": "Dmitry Shulga <d.shulga@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Reduce the time required for a database recovery from archive." }, { "msg_contents": "Greetings,\n\n* Dmitry Shulga (d.shulga@postgrespro.ru) wrote:\n> > On 9 Sep 2020, at 21:26, Stephen Frost <sfrost@snowman.net> wrote:\n> > * Dmitry Shulga (d.shulga@postgrespro.ru) wrote:\n> >> Overall archive file processing is done one by one, and this might\n> >> create a performance bottleneck if archived WAL files are delivered slowly,\n> >> because the database server has to wait for arrival of the next\n> >> WAL segment before applying its records.\n> >> \n> >> To address this issue it is proposed to receive archived WAL files in parallel\n> >> so that when the next WAL segment file is required for processing of redo log\n> >> records it would be already available.\n> > \n> > Yes, pgbackrest already does exactly this (if configured)- uses parallel\n> > processes to fetch the WAL and have it be available ahead of time.\n> \n> pgbackrest is a third-party software that should be additionally installed on customer's premises.\n> \n> On the other hand, built-in support of this optimization in PostgresSQL is a good argument to add\n> this feature and provide it to customers just out of the box.\n\nSure, having core do pre-fetching could be useful, though there's the\ndownside that it, unfortunately, can't know how much WAL is actually\ngoing to be needed as we play forward since we don't know where we will\nend up finding the target we've been asked for. Unlikely that'll be too\nmuch of an issue with the traditional 16 MB WAL files, but having a more\nintegrated backup/restore solution would be able to address that by\ntracking the restore targets that are in each WAL (which is something\nwe've had on our todo list for pgbackrest for a while, and that would\nalso let someone ask \"am I able to reach this restore target?\").\n\n> >> Implementation of this approach assumes running several background processes (bgworkers)\n> >> each of which runs a shell command specified by the parameter restore_command\n> >> to deliver an archived WAL file. Number of running parallel processes is limited\n> >> by the new parameter max_restore_command_workers. If this parameter has value 0\n> >> then WAL files delivery is performed using the original algorithm, that is in\n> >> one-by-one manner. If this parameter has value greater than 0 then the database\n> >> server starts several bgworker processes up to the limit specified by\n> >> the parameter max_restore_command_workers and passes to every process\n> >> WAL file name to deliver. Active processes start prefetching of specified\n> >> WAL files and store received files in the directory pg_wal/pgsql_tmp. After\n> >> bgworker process finishes receiving a file it marks itself as a free process\n> >> and waits for a new request to receive a next WAL file. The main process\n> >> performing database recovery still handles WAL files in one-by-one manner,\n> >> but instead of waiting for a next required WAL file's availability it checks for\n> >> that file in the prefetched directory. If a new file is present there,\n> >> the main process starts its processing.\n> > \n> > I'm a bit confused about this description- surely it makes sense for the\n> OK. The description I originally provided was probably pretty misleading so I will try to clarify it a bit.\n> \n> So, as soon as a bgworker process finishes delivering a WAL file it marks itself as a free.\n> \n> WAL records applier working in parallel and processing the WAL files in sequential manner.\n> Once it finishes handling of the current WAL file, it checks whether it is possible to run extra bgworker processes\n> to deliver WAL files which will be required a bit later. If there are free bgworker processes then applier requests \n> to start downloading of one or more extra WAL files. After that applier determines a name of next WAL file to handle\n> and checks whether it exist in the prefetching directory. If it does exist then applier starts handling it and\n> processing loop is repeated. \n\nOk- so the idea is that each time the applying process finishes with a\nWAL file then it'll see if there's an available worker and, if so, will\ngive it the next file to go get (which would presumably be some number\nin the future and the actual next file the applying process needs is\nalready available). That sounds better, at least, though I'm not sure\nwhy we're making it the job of the applying process to push the workers\neach time..? Also, I'm not sure about the interface- wouldn't it make\nmore sense to have a \"pre-fetch this amount of WAL\" kind of parameter\ndirectly instead of tying that to the number of background workers? You\nmight only need one or two processes doing WAL fetching to be able to\nfetch faster than the applying process is able to apply it, but you\nprobably want to pre-fetch more than just one or two 16 MB WAL files.\n\nIn other words, I would have thought we'd have:\n\nwal_prefetch_amount = 1GB\nmax_restore_command_workers = 2\n\nand then you'd have up to 2 worker processes running and they'd be\nkeeping 1GB of WAL pre-fetched at all times. If we have just\n'max_restore_command_workers' and you want to pre-fetch 1GB of WAL then\nyou'd have to have a pretty high value there and you'd end up with\na bunch of threads that all spike to go do work each time the applying\nprocess finishes a WAL file but then just sit around doing nothing while\nwaiting for the applying process to finish another segment.\n\nThanks,\n\nStephen", "msg_date": "Mon, 19 Oct 2020 12:25:51 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Reduce the time required for a database recovery from archive." }, { "msg_contents": "Hello Stephen,\n\n> On 19 Oct 2020, at 23:25, Stephen Frost <sfrost@snowman.net> wrote:\n> \n> Greetings,\n> \n>>>> Implementation of this approach assumes running several background processes (bgworkers)\n>>>> each of which runs a shell command specified by the parameter restore_command\n>>>> to deliver an archived WAL file. Number of running parallel processes is limited\n>>>> by the new parameter max_restore_command_workers. If this parameter has value 0\n>>>> then WAL files delivery is performed using the original algorithm, that is in\n>>>> one-by-one manner. If this parameter has value greater than 0 then the database\n>>>> server starts several bgworker processes up to the limit specified by\n>>>> the parameter max_restore_command_workers and passes to every process\n>>>> WAL file name to deliver. Active processes start prefetching of specified\n>>>> WAL files and store received files in the directory pg_wal/pgsql_tmp. After\n>>>> bgworker process finishes receiving a file it marks itself as a free process\n>>>> and waits for a new request to receive a next WAL file. The main process\n>>>> performing database recovery still handles WAL files in one-by-one manner,\n>>>> but instead of waiting for a next required WAL file's availability it checks for\n>>>> that file in the prefetched directory. If a new file is present there,\n>>>> the main process starts its processing.\n>>> \n>>> I'm a bit confused about this description- surely it makes sense for the\n>> OK. The description I originally provided was probably pretty misleading so I will try to clarify it a bit.\n>> \n>> So, as soon as a bgworker process finishes delivering a WAL file it marks itself as a free.\n>> \n>> WAL records applier working in parallel and processing the WAL files in sequential manner.\n>> Once it finishes handling of the current WAL file, it checks whether it is possible to run extra bgworker processes\n>> to deliver WAL files which will be required a bit later. If there are free bgworker processes then applier requests \n>> to start downloading of one or more extra WAL files. After that applier determines a name of next WAL file to handle\n>> and checks whether it exist in the prefetching directory. If it does exist then applier starts handling it and\n>> processing loop is repeated. \n> \n> Ok- so the idea is that each time the applying process finishes with a\n> WAL file then it'll see if there's an available worker and, if so, will\n> give it the next file to go get (which would presumably be some number\n> in the future and the actual next file the applying process needs is\n> already available). That sounds better, at least, though I'm not sure\n> why we're making it the job of the applying process to push the workers\n> each time..?\nEvery bgwork serves as a task to deliver a WAL file. Considering a task as an active entity is well-known approach in software design.\nSo I don't see any issues with such implementation. Moreover, implementation of this approach is probably simpler than any other alternatives\nand still providing positive performance impact in comparing with current (non optimized) implementation.\n\n> Also, I'm not sure about the interface- wouldn't it make\n> more sense to have a \"pre-fetch this amount of WAL\" kind of parameter\n> directly instead of tying that to the number of background workers?\nThis approach was originally considered and closely discussed.\nFinally, it was decided that introducing an extra GUC parameter to control pre-fetch limit is not practical since it shifts responsibility for tuning prefetching\nmechanism from postgres server to a user.\nFrom my point of view the fewer parameters exist to set up some feature the better.\n\n> You\n> might only need one or two processes doing WAL fetching to be able to\n> fetch faster than the applying process is able to apply it, but you\n> probably want to pre-fetch more than just one or two 16 MB WAL files.\n\n\nEvery time when prefetching is started a number of potentially prefetched files is calculated by expression\n\t PREFETCH_RATION * max_restore_command_workers - 'number of already prefetched files'\nwhere PREFETCH_RATION is compiled-in constant and has value 16.\n\nAfter that a task for delivering a next WAL file is placed to a current free bgworker process up until no more free bgworker processes.\n\n\n> In other words, I would have thought we'd have:\n> \n> wal_prefetch_amount = 1GB\n> max_restore_command_workers = 2\n> \n> and then you'd have up to 2 worker processes running and they'd be\n> keeping 1GB of WAL pre-fetched at all times. If we have just\n> 'max_restore_command_workers' and you want to pre-fetch 1GB of WAL then\n> you'd have to have a pretty high value there and you'd end up with\n> a bunch of threads that all spike to go do work each time the applying\nSorry, I don't see how we can end up with a bunch of threads?\nmax_restore_command_workers has value 2 in your example meaning that no more than 2 bgworkers could be run concurrently for the sake of WAL files prefetching \n\n> process finishes a WAL file but then just sit around doing nothing while\n> waiting for the applying process to finish another segment.\n\nI believe that for typical set-up the parameter max_restore_command_workers would have value 2 or 3 in order to supply\na delivered WAL file on time just before it be started processing.\n\nThis use case is for environment where time required for delivering WAL file from archive is greater than time required for applying records contained in the WAL file.\nIf time required for WAL file delivering lesser than than time required for handling records contained in it then max_restore_command_workers shouldn't be specified at all\n\n> \n> Thanks,\n> \n> Stephen\n\n\n\n", "msg_date": "Mon, 9 Nov 2020 22:44:25 +0700", "msg_from": "Dmitry Shulga <d.shulga@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Reduce the time required for a database recovery from archive." }, { "msg_contents": "Greetings,\n\n* Dmitry Shulga (d.shulga@postgrespro.ru) wrote:\n> > On 19 Oct 2020, at 23:25, Stephen Frost <sfrost@snowman.net> wrote:\n> >>>> Implementation of this approach assumes running several background processes (bgworkers)\n> >>>> each of which runs a shell command specified by the parameter restore_command\n> >>>> to deliver an archived WAL file. Number of running parallel processes is limited\n> >>>> by the new parameter max_restore_command_workers. If this parameter has value 0\n> >>>> then WAL files delivery is performed using the original algorithm, that is in\n> >>>> one-by-one manner. If this parameter has value greater than 0 then the database\n> >>>> server starts several bgworker processes up to the limit specified by\n> >>>> the parameter max_restore_command_workers and passes to every process\n> >>>> WAL file name to deliver. Active processes start prefetching of specified\n> >>>> WAL files and store received files in the directory pg_wal/pgsql_tmp. After\n> >>>> bgworker process finishes receiving a file it marks itself as a free process\n> >>>> and waits for a new request to receive a next WAL file. The main process\n> >>>> performing database recovery still handles WAL files in one-by-one manner,\n> >>>> but instead of waiting for a next required WAL file's availability it checks for\n> >>>> that file in the prefetched directory. If a new file is present there,\n> >>>> the main process starts its processing.\n> >>> \n> >>> I'm a bit confused about this description- surely it makes sense for the\n> >> OK. The description I originally provided was probably pretty misleading so I will try to clarify it a bit.\n> >> \n> >> So, as soon as a bgworker process finishes delivering a WAL file it marks itself as a free.\n> >> \n> >> WAL records applier working in parallel and processing the WAL files in sequential manner.\n> >> Once it finishes handling of the current WAL file, it checks whether it is possible to run extra bgworker processes\n> >> to deliver WAL files which will be required a bit later. If there are free bgworker processes then applier requests \n> >> to start downloading of one or more extra WAL files. After that applier determines a name of next WAL file to handle\n> >> and checks whether it exist in the prefetching directory. If it does exist then applier starts handling it and\n> >> processing loop is repeated. \n> > \n> > Ok- so the idea is that each time the applying process finishes with a\n> > WAL file then it'll see if there's an available worker and, if so, will\n> > give it the next file to go get (which would presumably be some number\n> > in the future and the actual next file the applying process needs is\n> > already available). That sounds better, at least, though I'm not sure\n> > why we're making it the job of the applying process to push the workers\n> > each time..?\n> Every bgwork serves as a task to deliver a WAL file. Considering a task as an active entity is well-known approach in software design.\n> So I don't see any issues with such implementation. Moreover, implementation of this approach is probably simpler than any other alternatives\n> and still providing positive performance impact in comparing with current (non optimized) implementation.\n\nI don't think we look only at if something is an improvement or not over\nthe current situation when we consider changes.\n\nThe relatively simple approach I was thinking was that a couple of\nworkers would be started and they'd have some prefetch amount that needs\nto be kept out ahead of the applying process, which they could\npotentially calculate themselves without needing to be pushed forward by\nthe applying process.\n\n> > Also, I'm not sure about the interface- wouldn't it make\n> > more sense to have a \"pre-fetch this amount of WAL\" kind of parameter\n> > directly instead of tying that to the number of background workers?\n> This approach was originally considered and closely discussed.\n> Finally, it was decided that introducing an extra GUC parameter to control pre-fetch limit is not practical since it shifts responsibility for tuning prefetching\n> mechanism from postgres server to a user.\n> From my point of view the fewer parameters exist to set up some feature the better.\n\nI agree in general that it's better to have fewer parameters, but I\ndisagree that this isn't an important option for users to be able to\ntune- the rate of fetching WAL and of applying WAL varies quite a bit\nfrom system to system. Being able to tune the pre-fetch seems like it'd\nactually be more important to a user than the number of processes\nrequired to keep up with that amount of pre-fetching, which is something\nwe could actually figure out on our own...\n\n> > You\n> > might only need one or two processes doing WAL fetching to be able to\n> > fetch faster than the applying process is able to apply it, but you\n> > probably want to pre-fetch more than just one or two 16 MB WAL files.\n> \n> Every time when prefetching is started a number of potentially prefetched files is calculated by expression\n> \t PREFETCH_RATION * max_restore_command_workers - 'number of already prefetched files'\n> where PREFETCH_RATION is compiled-in constant and has value 16.\n> \n> After that a task for delivering a next WAL file is placed to a current free bgworker process up until no more free bgworker processes.\n\nAh, it wasn't mentioned that we've got a multiplier in here, but it\nstill ends up meaning that if a user actually wants to tune the amount\nof pre-fetching being done, they're going to end up having to tune the,\npretty much entirely unrelated, value of max_restore_command_workers.\nThat really seems entirely backwards to me from what I would think the\nuser would actually want to tune.\n\n> > In other words, I would have thought we'd have:\n> > \n> > wal_prefetch_amount = 1GB\n> > max_restore_command_workers = 2\n> > \n> > and then you'd have up to 2 worker processes running and they'd be\n> > keeping 1GB of WAL pre-fetched at all times. If we have just\n> > 'max_restore_command_workers' and you want to pre-fetch 1GB of WAL then\n> > you'd have to have a pretty high value there and you'd end up with\n> > a bunch of threads that all spike to go do work each time the applying\n> Sorry, I don't see how we can end up with a bunch of threads?\n> max_restore_command_workers has value 2 in your example meaning that no more than 2 bgworkers could be run concurrently for the sake of WAL files prefetching \n\nIf you don't give the user the option to configure the prefetch amount,\nexcept indirectly by changing the number of max restore workers, then to\nget a higher prefetch amount they have to increase the number of\nworkers. That's what I'm referring to above, and previously, here.\n\n> > process finishes a WAL file but then just sit around doing nothing while\n> > waiting for the applying process to finish another segment.\n> \n> I believe that for typical set-up the parameter max_restore_command_workers would have value 2 or 3 in order to supply\n> a delivered WAL file on time just before it be started processing.\n> \n> This use case is for environment where time required for delivering WAL file from archive is greater than time required for applying records contained in the WAL file.\n> If time required for WAL file delivering lesser than than time required for handling records contained in it then max_restore_command_workers shouldn't be specified at all\n\nThat's certainly not correct at all- the two aren't really all that\nrelated, because any time spent waiting for a WAL file to be delivered\nis time that the applying process *could* be working to apply WAL\ninstead of waiting. At a minimum, I'd expect us to want to have, by\ndefault, at least one worker process running out in front of the\napplying process to hopefully eliminate most, if not all, time where the\napplying process is waiting for a WAL to show up. In cases where the\napplying process is faster than a single fetching process, a user might\nwant to have two or more restore workers, though ultimately I still\ncontend that what they really want is as many workers as needed to make\nsure that the applying process doesn't ever need to wait- up to some\nlimit based on the amount of space that's available.\n\nAnd back to the configuration side of this- have you considered the\nchallenge that a user who is using very large WAL files might run\ninto with the proposed approach that doesn't allow them to control the\namount of space used? If I'm using 1G WAL files, then I need to have\n16G available to have *any* pre-fetching done with this proposed\napproach, right? That doesn't seem great.\n\nThanks,\n\nStephen", "msg_date": "Mon, 9 Nov 2020 11:31:59 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Reduce the time required for a database recovery from archive." }, { "msg_contents": "On 09.11.2020 19:31, Stephen Frost wrote:\n> Greetings,\n>\n> * Dmitry Shulga (d.shulga@postgrespro.ru) wrote:\n>>> On 19 Oct 2020, at 23:25, Stephen Frost <sfrost@snowman.net> wrote:\n>>>\n>>> process finishes a WAL file but then just sit around doing nothing while\n>>> waiting for the applying process to finish another segment.\n>> I believe that for typical set-up the parameter max_restore_command_workers would have value 2 or 3 in order to supply\n>> a delivered WAL file on time just before it be started processing.\n>>\n>> This use case is for environment where time required for delivering WAL file from archive is greater than time required for applying records contained in the WAL file.\n>> If time required for WAL file delivering lesser than than time required for handling records contained in it then max_restore_command_workers shouldn't be specified at all\n> That's certainly not correct at all- the two aren't really all that\n> related, because any time spent waiting for a WAL file to be delivered\n> is time that the applying process *could* be working to apply WAL\n> instead of waiting. At a minimum, I'd expect us to want to have, by\n> default, at least one worker process running out in front of the\n> applying process to hopefully eliminate most, if not all, time where the\n> applying process is waiting for a WAL to show up. In cases where the\n> applying process is faster than a single fetching process, a user might\n> want to have two or more restore workers, though ultimately I still\n> contend that what they really want is as many workers as needed to make\n> sure that the applying process doesn't ever need to wait- up to some\n> limit based on the amount of space that's available.\n>\n> And back to the configuration side of this- have you considered the\n> challenge that a user who is using very large WAL files might run\n> into with the proposed approach that doesn't allow them to control the\n> amount of space used? If I'm using 1G WAL files, then I need to have\n> 16G available to have *any* pre-fetching done with this proposed\n> approach, right? That doesn't seem great.\n>\n> Thanks,\n>\n> Stephen\n\nStatus update for a commitfest entry.\n\nThe commitfest is closed now. As this entry has been Waiting on Author \nfor a while, I've marked it as returned with feedback. Dmitry, feel free \nto resubmit an updated version to a future commitfest.\n\n-- \nAnastasia Lubennikova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Tue, 1 Dec 2020 18:05:43 +0300", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Reduce the time required for a database recovery from archive." }, { "msg_contents": "Hi Stephen\n\nBased on our last discussion I redesigned the implementation of WAL archive recovery speed-up. The main idea of the new implementation was partly borrowed from your proposal, to be more accurate from the following one:\n\n> On 9 Nov 2020, at 23:31, Stephen Frost <sfrost@snowman.net> wrote:\n> \n> The relatively simple approach I was thinking was that a couple of\n> workers would be started and they'd have some prefetch amount that needs\n> to be kept out ahead of the applying process, which they could\n> potentially calculate themselves without needing to be pushed forward by\n> the applying process.\n> \nIn the new implementation, several workers are spawned on server start up for delivering WAL segements from archive. The number of workers to spawn is specfied by the GUC parameter wal_prefetch_workers; the max. number of files to preload from the archive is determined by the GUC parameter wal_max_prefetch_amount. The applier of WAL records still handles WAL files one-by-one, but since several prefetching processes are loading files from the archive, there is a high probability that when the next WAL file is requested by the applier of WAL records, it has already been delivered from the archive.\n\nEvery time any of the running workers is going to preload the next WAL file, it checks whether a limit imposed by the parameter wal_max_prefetch_amount was reached. If it was, then the process suspends preloading until the WAL applier process handles some of the already preloaded WAL files and the total number of already loaded but not yet processed WAL files drops below this limit.\n\nAt the moment I didn't implement a mechanism for dynamic calculation of the number of workers required for loading the WAL files in time. We can consider current (simplified) implementation as a base for further discussion and turn to this matter in the next iteration if it be needed.\n\nAlso I would like to ask your opinion about the issue I'm thinking about:\n Parallel workers spawned for preloading WAL files from archive use the original mechanism for delivering files from archive - they run a command specified by the GUC parameter restore_command. One of the possible parameters accepted by the restore_command is %r, which specifies the filename of the last restart point. If several workers preload WAL files simultaneously with another process applying the preloaded WAL files, I’m not sure what is correct way to determine the last restart point value that WAL-preloading processes should use, because this value can be updated at any time by the process that applies WALs.\n\nAnother issue that I would like to ask your opinion about regards to choosing correct value for a max size of the hash table stored in shared memory. Currently, wal_max_prefetch_amount is passed as the value for max. hash table size that I'm not sure is the best decision.\n\nThanks in advance for feedback.\n\nRegards,\nDmitry", "msg_date": "Mon, 11 Jan 2021 14:51:23 +0700", "msg_from": "Dmitry Shulga <d.shulga@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Reduce the time required for a database recovery from archive." }, { "msg_contents": "Hi Dimtry,\n\nOn 1/11/21 2:51 AM, Dmitry Shulga wrote:\n> Hi Stephen\n> \n> Based on our last discussion I redesigned the implementation of WAL \n> archive recovery speed-up. \n\nSeems like there should have been a patch attached? In any case the \ncurrent patch no longer applies so marked Waiting on Author.\n\nPersonally, I'm not too keen on this patch as implemented. Several \nthird-party backup solutions support parallel archive get so it would be \nnice to support an interface that simply says to the restore_command, \n\"go get 1gb of WAL and write the files here.\" This patch still assumes \nthat the user has written their own restore command, which is \nthird-party by definition, so I can't see how interfacing with \nthird-party software is an issue here.\n\nAlso, having multiple workers blindly asking for WAL can cause quite a \nbit of traffic and cost because PG knows what WAL it wants but it \ndoesn't know what exists. On the other hand, a backup solution can \ncheaply determine what is available to prevent hammering the archive \nwith requests for files that don't exist.\n\nRegards,\n-- \n-David\ndavid@pgmasters.net\n\n\n", "msg_date": "Thu, 18 Mar 2021 11:04:19 -0400", "msg_from": "David Steele <david@pgmasters.net>", "msg_from_op": false, "msg_subject": "Re: Reduce the time required for a database recovery from archive." }, { "msg_contents": "\n\n> 18 марта 2021 г., в 20:04, David Steele <david@pgmasters.net> написал(а):\n> it would be nice to support an interface that simply says to the restore_command, \"go get 1gb of WAL and write the files here.\"\n\n+1 to redesigning restore_command and archive_command.\n\nBest regards, Andrey Borodin.\n\n\n\n", "msg_date": "Thu, 18 Mar 2021 20:37:57 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Reduce the time required for a database recovery from archive." }, { "msg_contents": "On 3/18/21 11:37 AM, Andrey Borodin wrote:\n> \n> \n>> 18 марта 2021 г., в 20:04, David Steele <david@pgmasters.net> написал(а):\n>> it would be nice to support an interface that simply says to the restore_command, \"go get 1gb of WAL and write the files here.\"\n> \n> +1 to redesigning restore_command and archive_command.\n\nIndeed, archive_command would benefit from the same treatment. The need \nto call archive_command for each WAL segment even when parallel \nprocessing is going on behind the scenes is a bottleneck.\n\nLarger WAL segments sizes can be used to mitigate this issue but an \nimprovement would be welcome.\n\nRegards,\n-- \n-David\ndavid@pgmasters.net\n\n\n", "msg_date": "Thu, 18 Mar 2021 11:46:38 -0400", "msg_from": "David Steele <david@pgmasters.net>", "msg_from_op": false, "msg_subject": "Re: Reduce the time required for a database recovery from archive." }, { "msg_contents": "Hello everyone in this thread!\n\nOn 2021-03-18 18:04, David Steele wrote:\n> Seems like there should have been a patch attached?\n\nIMO there's a technical problem with sending, receiving (or displaying \non the site) emails from the list pgsql-hackers. By subsribing to this \nlist I received the attached patch from the email [1]. And my colleague \nRoman Zharkov said that the button 'Resend email' from that link helped \nhim to receive the email with the attached patch. On the other hand \nfollwing this link in the browser I do not see the attached patch. Do \nyou think it is worth to write about this issue to \nwebmaster(dot)postgresql(dot)org?..\n\nJust in case I'm lucky this email contains the lost patch.\n\n[1] \nhttps://www.postgresql.org/message-id/4047CC05-1AF5-454B-850B-ED37374A2AC0%40postgrespro.ru\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 19 Mar 2021 11:32:53 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Reduce the time required for a database recovery from archive." }, { "msg_contents": "On 3/19/21 4:32 AM, Marina Polyakova wrote:\n> \n> On 2021-03-18 18:04, David Steele wrote:\n>> Seems like there should have been a patch attached?\n> \n> IMO there's a technical problem with sending, receiving (or displaying \n> on the site) emails from the list pgsql-hackers. By subsribing to this \n> list I received the attached patch from the email [1]. And my colleague \n> Roman Zharkov said that the button 'Resend email' from that link helped \n> him to receive the email with the attached patch. On the other hand \n> follwing this link in the browser I do not see the attached patch. Do \n> you think it is worth to write about this issue to \n> webmaster(dot)postgresql(dot)org?..\n> \n> Just in case I'm lucky this email contains the lost patch.\n\nYou are correct -- if I send the email to myself I can see the patch (I \ncan also see it on the website in raw form). I usually read the thread \non the website before replying and I did not notice that the actual \nemail had an attachment.\n\nMy guess about why it is not showing up on the website is that the \nencoding is a bit unusual (quoted-printable vs base64). Or it may have \nto do with the inclusion of an HTML version of the message. You are \nwelcome to followup with the webmaster and see if this is a known issue.\n\nRegards,\n-- \n-David\ndavid@pgmasters.net\n\n\n", "msg_date": "Fri, 19 Mar 2021 08:50:06 -0400", "msg_from": "David Steele <david@pgmasters.net>", "msg_from_op": false, "msg_subject": "Re: Reduce the time required for a database recovery from archive." } ]
[ { "msg_contents": "We use the timestamp of the global statfile if we are not able to\ndetermine it for a particular database either because the entry for\nthat database doesn't exist or there is an error while reading the\nspecific database entry. This was not taken care of while reading\nother entries like ArchiverStats or SLRUStats. See\npgstat_read_db_statsfile_timestamp. I have observed this while\nreviewing Sawada-San's patch related to logical replication stats [1].\n\nI think this can only happen if due to some reason the statfile got\ncorrupt or we\nhave some bug in stats writing code, the chances of both are rare and even\nif that happens we will use stale statistics.\n\nThe attached patch by Sawada-San will fix this issue. As the chances of this\nthe problem is rare and nobody has reported any issue related to this,\nso it might be okay not to backpatch this.\n\nThoughts?\n\n[1] - https://www.postgresql.org/message-id/CAA4eK1JBqQh9cBKjO-nKOOE%3D7f6ONDCZp0TJZfn4VsQqRZ%2BuYA%40mail.gmail.com\n\n-- \nWith Regards,\nAmit Kapila.", "msg_date": "Tue, 8 Sep 2020 11:40:18 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": true, "msg_subject": "Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On Tue, Sep 8, 2020 at 8:10 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> We use the timestamp of the global statfile if we are not able to\n> determine it for a particular database either because the entry for\n> that database doesn't exist or there is an error while reading the\n> specific database entry. This was not taken care of while reading\n> other entries like ArchiverStats or SLRUStats. See\n> pgstat_read_db_statsfile_timestamp. I have observed this while\n> reviewing Sawada-San's patch related to logical replication stats [1].\n>\n> I think this can only happen if due to some reason the statfile got\n> corrupt or we\n> have some bug in stats writing code, the chances of both are rare and even\n> if that happens we will use stale statistics.\n>\n> The attached patch by Sawada-San will fix this issue. As the chances of\n> this\n> the problem is rare and nobody has reported any issue related to this,\n> so it might be okay not to backpatch this.\n>\n> Thoughts?\n>\n>\nWhy are we reading the archiver statis and and slru stats in\n\"pgstat_read_db_statsfile_timestamp\" in the first place? That seems well\nout of scope for that function.\n\nIf nothing else the comment at the top of that function is out of touch\nwith reality. We do seem to read it into local buffers and then ignore the\ncontents. I guess we're doing it just to verify that it's not corrupt -- so\nperhaps the function should actually have a different name than it does\nnow, since it certainly seems to do more than actually read the statsfile\ntimestamp.\n\nSpecifically in this patch it looks wrong -- in the case of say the SLRU\nstats being corrupt, we will now return the timestamp of the global stats\nfile even if there is one existing for the database requested, which\ndefinitely breaks the contract of the function. It's already broken, but\nthis doesn't seem to make it less so.\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 Tue, Sep 8, 2020 at 8:10 AM Amit Kapila <amit.kapila16@gmail.com> wrote:We use the timestamp of the global statfile if we are not able to\ndetermine it for a particular database either because the entry for\nthat database doesn't exist or there is an error while reading the\nspecific database entry. This was not taken care of while reading\nother entries like ArchiverStats or SLRUStats. See\npgstat_read_db_statsfile_timestamp. I have observed this while\nreviewing Sawada-San's patch related to logical replication stats [1].\n\nI think this can only happen if due to some reason the statfile got\ncorrupt or we\nhave some bug in stats writing code, the chances of both are rare and even\nif that happens we will use stale statistics.\n\nThe attached patch by Sawada-San will fix this issue. As the chances of this\nthe problem is rare and nobody has reported any issue related to this,\nso it might be okay not to backpatch this.\n\nThoughts?Why are we reading the archiver statis and and slru stats in \"pgstat_read_db_statsfile_timestamp\" in the first place? That seems well out of scope for that function.If nothing else the comment at the top of that function is out of touch with reality. We do seem to read it into local buffers and then ignore the contents. I guess we're doing it just to verify that it's not corrupt -- so perhaps the function should actually have a different name than it does now, since it certainly seems to do more than actually read the statsfile timestamp.Specifically in this patch it looks wrong -- in the case of say the SLRU stats being corrupt, we will now return the timestamp of the global stats file even if there is one existing for the database requested, which definitely breaks the contract of the function. It's already broken, but this doesn't seem to make it less so.--  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Tue, 8 Sep 2020 12:28:02 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "\n\nOn 2020/09/08 19:28, Magnus Hagander wrote:\n> \n> \n> On Tue, Sep 8, 2020 at 8:10 AM Amit Kapila <amit.kapila16@gmail.com <mailto:amit.kapila16@gmail.com>> wrote:\n> \n> We use the timestamp of the global statfile if we are not able to\n> determine it for a particular database either because the entry for\n> that database doesn't exist or there is an error while reading the\n> specific database entry. This was not taken care of while reading\n> other entries like ArchiverStats or SLRUStats. See\n> pgstat_read_db_statsfile_timestamp. I have observed this while\n> reviewing Sawada-San's patch related to logical replication stats [1].\n> \n> I think this can only happen if due to some reason the statfile got\n> corrupt or we\n> have some bug in stats writing code, the chances of both are rare and even\n> if that happens we will use stale statistics.\n> \n> The attached patch by Sawada-San will fix this issue. As the chances of this\n> the problem is rare and nobody has reported any issue related to this,\n> so it might be okay not to backpatch this.\n> \n> Thoughts?\n> \n> \n> Why are we reading the archiver statis and and slru stats in \"pgstat_read_db_statsfile_timestamp\" in the first place?\n\nMaybe because they are written before database stats entries? That is,\nto read the target database stats entry and get the timestamp from it,\nwe need to read (or lseek) all the global stats entries written before them.\n\n\n> That seems well out of scope for that function.\n> \n> If nothing else the comment at the top of that function is out of touch with reality. We do seem to read it into local buffers and then ignore the contents. I guess we're doing it just to verify that it's not corrupt -- so perhaps the function should actually have a different name than it does now, since it certainly seems to do more than actually read the statsfile timestamp.\n> \n> Specifically in this patch it looks wrong -- in the case of say the SLRU stats being corrupt, we will now return the timestamp of the global stats file even if there is one existing for the database requested, which definitely breaks the contract of the function.\n\nYes.\nWe should return false when fread() for database entry fails, instead? That is,\n\n1. If corrupted stats file is found, the function always returns false.\n2. If the file is not currupted and the target database entry is found, its timestamp is returned.\n3. If the file is not corrupted and the target is NOT found, the timestamp of global entry is returned.\n\nRegards,\n\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Tue, 8 Sep 2020 22:11:01 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On Tue, Sep 8, 2020 at 3:11 PM Fujii Masao <masao.fujii@oss.nttdata.com>\nwrote:\n\n>\n>\n> On 2020/09/08 19:28, Magnus Hagander wrote:\n> >\n> >\n> > On Tue, Sep 8, 2020 at 8:10 AM Amit Kapila <amit.kapila16@gmail.com\n> <mailto:amit.kapila16@gmail.com>> wrote:\n> >\n> > We use the timestamp of the global statfile if we are not able to\n> > determine it for a particular database either because the entry for\n> > that database doesn't exist or there is an error while reading the\n> > specific database entry. This was not taken care of while reading\n> > other entries like ArchiverStats or SLRUStats. See\n> > pgstat_read_db_statsfile_timestamp. I have observed this while\n> > reviewing Sawada-San's patch related to logical replication stats\n> [1].\n> >\n> > I think this can only happen if due to some reason the statfile got\n> > corrupt or we\n> > have some bug in stats writing code, the chances of both are rare\n> and even\n> > if that happens we will use stale statistics.\n> >\n> > The attached patch by Sawada-San will fix this issue. As the chances\n> of this\n> > the problem is rare and nobody has reported any issue related to\n> this,\n> > so it might be okay not to backpatch this.\n> >\n> > Thoughts?\n> >\n> >\n> > Why are we reading the archiver statis and and slru stats in\n> \"pgstat_read_db_statsfile_timestamp\" in the first place?\n>\n> Maybe because they are written before database stats entries? That is,\n> to read the target database stats entry and get the timestamp from it,\n> we need to read (or lseek) all the global stats entries written before\n> them.\n>\n>\nOh meh. Yeah, I'm reading this thing completely wrong :/ Ignore my comments\n:)\n\n\n\n> That seems well out of scope for that function.\n> >\n> > If nothing else the comment at the top of that function is out of touch\n> with reality. We do seem to read it into local buffers and then ignore the\n> contents. I guess we're doing it just to verify that it's not corrupt -- so\n> perhaps the function should actually have a different name than it does\n> now, since it certainly seems to do more than actually read the statsfile\n> timestamp.\n> >\n> > Specifically in this patch it looks wrong -- in the case of say the SLRU\n> stats being corrupt, we will now return the timestamp of the global stats\n> file even if there is one existing for the database requested, which\n> definitely breaks the contract of the function.\n>\n> Yes.\n> We should return false when fread() for database entry fails, instead?\n> That is,\n>\n> 1. If corrupted stats file is found, the function always returns false.\n> 2. If the file is not currupted and the target database entry is found,\n> its timestamp is returned.\n> 3. If the file is not corrupted and the target is NOT found, the timestamp\n> of global entry is returned\n>\n\nYeah, with more coffee and re-reading it, I'm not sure how we could have\nthe database stats being OK if the archiver or slru stats are not.\n\nThat said, I think it still makes sense to return false if the stats file\nis corrupt. How much can we trust the first block, if the block right after\nit is corrupt? So yeah, I think your described order seems correct. But\nthat's also what the code already did before this patch, isn't 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 Tue, Sep 8, 2020 at 3:11 PM Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\n\nOn 2020/09/08 19:28, Magnus Hagander wrote:\n> \n> \n> On Tue, Sep 8, 2020 at 8:10 AM Amit Kapila <amit.kapila16@gmail.com <mailto:amit.kapila16@gmail.com>> wrote:\n> \n>     We use the timestamp of the global statfile if we are not able to\n>     determine it for a particular database either because the entry for\n>     that database doesn't exist or there is an error while reading the\n>     specific database entry. This was not taken care of while reading\n>     other entries like ArchiverStats or SLRUStats. See\n>     pgstat_read_db_statsfile_timestamp. I have observed this while\n>     reviewing Sawada-San's patch related to logical replication stats [1].\n> \n>     I think this can only happen if due to some reason the statfile got\n>     corrupt or we\n>     have some bug in stats writing code, the chances of both are rare and even\n>     if that happens we will use stale statistics.\n> \n>     The attached patch by Sawada-San will fix this issue. As the chances of this\n>     the problem is rare and nobody has reported any issue related to this,\n>     so it might be okay not to backpatch this.\n> \n>     Thoughts?\n> \n> \n> Why are we reading the archiver statis and and slru stats in \"pgstat_read_db_statsfile_timestamp\" in the first place?\n\nMaybe because they are written before database stats entries? That is,\nto read the target database stats entry and get the timestamp from it,\nwe need to read (or lseek) all the global stats entries written before them.\nOh meh. Yeah, I'm reading this thing completely wrong :/ Ignore my comments :)\n> That seems well out of scope for that function.\n> \n> If nothing else the comment at the top of that function is out of touch with reality. We do seem to read it into local buffers and then ignore the contents. I guess we're doing it just to verify that it's not corrupt -- so perhaps the function should actually have a different name than it does now, since it certainly seems to do more than actually read the statsfile timestamp.\n> \n> Specifically in this patch it looks wrong -- in the case of say the SLRU stats being corrupt, we will now return the timestamp of the global stats file even if there is one existing for the database requested, which definitely breaks the contract of the function.\n\nYes.\nWe should return false when fread() for database entry fails, instead? That is,\n\n1. If corrupted stats file is found, the function always returns false.\n2. If the file is not currupted and the target database entry is found, its timestamp is returned.\n3. If the file is not corrupted and the target is NOT found, the timestamp of global entry is returnedYeah, with more coffee and re-reading it, I'm not sure how we could have the database stats being OK if the archiver or slru stats are not.That said, I think it still makes sense to return false if the stats file is corrupt. How much can we trust the first block, if the block right after it is corrupt? So yeah, I think your described order seems correct. But that's also what the code already did before this patch, isn't it?--  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Tue, 8 Sep 2020 15:32:52 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On Tue, Sep 8, 2020 at 7:03 PM Magnus Hagander <magnus@hagander.net> wrote:\n>\n> On Tue, Sep 8, 2020 at 3:11 PM Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\n>>\n>>\n>>\n>> On 2020/09/08 19:28, Magnus Hagander wrote:\n>> >\n>> >\n>> > On Tue, Sep 8, 2020 at 8:10 AM Amit Kapila <amit.kapila16@gmail.com <mailto:amit.kapila16@gmail.com>> wrote:\n>> >\n>> > We use the timestamp of the global statfile if we are not able to\n>> > determine it for a particular database either because the entry for\n>> > that database doesn't exist or there is an error while reading the\n>> > specific database entry. This was not taken care of while reading\n>> > other entries like ArchiverStats or SLRUStats. See\n>> > pgstat_read_db_statsfile_timestamp. I have observed this while\n>> > reviewing Sawada-San's patch related to logical replication stats [1].\n>> >\n>> > I think this can only happen if due to some reason the statfile got\n>> > corrupt or we\n>> > have some bug in stats writing code, the chances of both are rare and even\n>> > if that happens we will use stale statistics.\n>> >\n>> > The attached patch by Sawada-San will fix this issue. As the chances of this\n>> > the problem is rare and nobody has reported any issue related to this,\n>> > so it might be okay not to backpatch this.\n>> >\n>> > Thoughts?\n>> >\n>> >\n>> > Why are we reading the archiver statis and and slru stats in \"pgstat_read_db_statsfile_timestamp\" in the first place?\n>>\n>> Maybe because they are written before database stats entries? That is,\n>> to read the target database stats entry and get the timestamp from it,\n>> we need to read (or lseek) all the global stats entries written before them.\n>>\n>\n> Oh meh. Yeah, I'm reading this thing completely wrong :/ Ignore my comments :)\n>\n>\n>\n>> > That seems well out of scope for that function.\n>> >\n>> > If nothing else the comment at the top of that function is out of touch with reality. We do seem to read it into local buffers and then ignore the contents. I guess we're doing it just to verify that it's not corrupt -- so perhaps the function should actually have a different name than it does now, since it certainly seems to do more than actually read the statsfile timestamp.\n>> >\n>> > Specifically in this patch it looks wrong -- in the case of say the SLRU stats being corrupt, we will now return the timestamp of the global stats file even if there is one existing for the database requested, which definitely breaks the contract of the function.\n>>\n>> Yes.\n>> We should return false when fread() for database entry fails, instead? That is,\n>>\n>> 1. If corrupted stats file is found, the function always returns false.\n>> 2. If the file is not currupted and the target database entry is found, its timestamp is returned.\n>> 3. If the file is not corrupted and the target is NOT found, the timestamp of global entry is returned\n>\n>\n> Yeah, with more coffee and re-reading it, I'm not sure how we could have the database stats being OK if the archiver or slru stats are not.\n>\n> That said, I think it still makes sense to return false if the stats file is corrupt. How much can we trust the first block, if the block right after it is corrupt? So yeah, I think your described order seems correct. But that's also what the code already did before this patch, isn't it?\n>\n\nNo, before patch as well, if we can't read the DB entry say because\nthe file is corrupt, we return true and use timestamp of global stats\nfile and this is what is established by the original commit 187492b6.\nSo, if we consider that as correct then the functionality is something\nlike once we have read the timestamp of the global statfile, we use\nthat if we can't read the actual db entry for whatever reason. It\nseems if we return false, the caller will call this function again in\nthe loop. Now, I see the point that if we can't read some part of the\nfile we should return false instead but not sure if that is helpful\nfrom the perspective of the caller of\npgstat_read_db_statsfile_timestamp.\n\nI have included Alvaro as he is a committer for 187492b6, so he might\nremember something and let us know if this is a mistake or there is\nsome reason for doing so (return true even when the db entry we are\ntrying to read is corrupt).\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Wed, 9 Sep 2020 08:34:03 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "\n\nOn 2020/09/09 12:04, Amit Kapila wrote:\n> On Tue, Sep 8, 2020 at 7:03 PM Magnus Hagander <magnus@hagander.net> wrote:\n>>\n>> On Tue, Sep 8, 2020 at 3:11 PM Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\n>>>\n>>>\n>>>\n>>> On 2020/09/08 19:28, Magnus Hagander wrote:\n>>>>\n>>>>\n>>>> On Tue, Sep 8, 2020 at 8:10 AM Amit Kapila <amit.kapila16@gmail.com <mailto:amit.kapila16@gmail.com>> wrote:\n>>>>\n>>>> We use the timestamp of the global statfile if we are not able to\n>>>> determine it for a particular database either because the entry for\n>>>> that database doesn't exist or there is an error while reading the\n>>>> specific database entry. This was not taken care of while reading\n>>>> other entries like ArchiverStats or SLRUStats. See\n>>>> pgstat_read_db_statsfile_timestamp. I have observed this while\n>>>> reviewing Sawada-San's patch related to logical replication stats [1].\n>>>>\n>>>> I think this can only happen if due to some reason the statfile got\n>>>> corrupt or we\n>>>> have some bug in stats writing code, the chances of both are rare and even\n>>>> if that happens we will use stale statistics.\n>>>>\n>>>> The attached patch by Sawada-San will fix this issue. As the chances of this\n>>>> the problem is rare and nobody has reported any issue related to this,\n>>>> so it might be okay not to backpatch this.\n>>>>\n>>>> Thoughts?\n>>>>\n>>>>\n>>>> Why are we reading the archiver statis and and slru stats in \"pgstat_read_db_statsfile_timestamp\" in the first place?\n>>>\n>>> Maybe because they are written before database stats entries? That is,\n>>> to read the target database stats entry and get the timestamp from it,\n>>> we need to read (or lseek) all the global stats entries written before them.\n>>>\n>>\n>> Oh meh. Yeah, I'm reading this thing completely wrong :/ Ignore my comments :)\n>>\n>>\n>>\n>>>> That seems well out of scope for that function.\n>>>>\n>>>> If nothing else the comment at the top of that function is out of touch with reality. We do seem to read it into local buffers and then ignore the contents. I guess we're doing it just to verify that it's not corrupt -- so perhaps the function should actually have a different name than it does now, since it certainly seems to do more than actually read the statsfile timestamp.\n>>>>\n>>>> Specifically in this patch it looks wrong -- in the case of say the SLRU stats being corrupt, we will now return the timestamp of the global stats file even if there is one existing for the database requested, which definitely breaks the contract of the function.\n>>>\n>>> Yes.\n>>> We should return false when fread() for database entry fails, instead? That is,\n>>>\n>>> 1. If corrupted stats file is found, the function always returns false.\n>>> 2. If the file is not currupted and the target database entry is found, its timestamp is returned.\n>>> 3. If the file is not corrupted and the target is NOT found, the timestamp of global entry is returned\n>>\n>>\n>> Yeah, with more coffee and re-reading it, I'm not sure how we could have the database stats being OK if the archiver or slru stats are not.\n>>\n>> That said, I think it still makes sense to return false if the stats file is corrupt. How much can we trust the first block, if the block right after it is corrupt? So yeah, I think your described order seems correct. But that's also what the code already did before this patch, isn't it?\n>>\n> \n> No, before patch as well, if we can't read the DB entry say because\n> the file is corrupt, we return true and use timestamp of global stats\n> file and this is what is established by the original commit 187492b6.\n> So, if we consider that as correct then the functionality is something\n> like once we have read the timestamp of the global statfile, we use\n> that if we can't read the actual db entry for whatever reason. It\n> seems if we return false, the caller will call this function again in\n> the loop. Now, I see the point that if we can't read some part of the\n> file we should return false instead but not sure if that is helpful\n> from the perspective of the caller of\n> pgstat_read_db_statsfile_timestamp.\n\nWhen false is returned, the caller backend_read_statsfile() seems to\nrequest the stats collector to write a fresh stats data into the file,\nand then pgstat_read_db_statsfile_timestamp() can try to read the fresh\nfile that may not be corrupted. So returning false in that case seems ok\nto me...\n\nRegards,\n\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Wed, 9 Sep 2020 14:24:25 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On Wed, Sep 9, 2020 at 10:54 AM Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\n>\n> On 2020/09/09 12:04, Amit Kapila wrote:\n> >\n> > No, before patch as well, if we can't read the DB entry say because\n> > the file is corrupt, we return true and use timestamp of global stats\n> > file and this is what is established by the original commit 187492b6.\n> > So, if we consider that as correct then the functionality is something\n> > like once we have read the timestamp of the global statfile, we use\n> > that if we can't read the actual db entry for whatever reason. It\n> > seems if we return false, the caller will call this function again in\n> > the loop. Now, I see the point that if we can't read some part of the\n> > file we should return false instead but not sure if that is helpful\n> > from the perspective of the caller of\n> > pgstat_read_db_statsfile_timestamp.\n>\n> When false is returned, the caller backend_read_statsfile() seems to\n> request the stats collector to write a fresh stats data into the file,\n> and then pgstat_read_db_statsfile_timestamp() can try to read the fresh\n> file that may not be corrupted. So returning false in that case seems ok\n> to me...\n>\n\nHmm, the request to get fresh data is sent irrespective of true or\nfalse. We send it to get the latest data if it is not present and it\nis not guaranteed that the request will lead to a write of stats file.\nSo, I am not sure if we can override that with the corrupted file\ncase, sure there is something to it but if we really want to rely on\nthat mechanism we should explicitly send such a request on detection\nof a corrupted file.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Wed, 9 Sep 2020 12:41:23 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On Wed, Sep 9, 2020 at 5:04 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> On Tue, Sep 8, 2020 at 7:03 PM Magnus Hagander <magnus@hagander.net>\n> wrote:\n> >\n> > On Tue, Sep 8, 2020 at 3:11 PM Fujii Masao <masao.fujii@oss.nttdata.com>\n> wrote:\n> >>\n> >>\n> >>\n> >> On 2020/09/08 19:28, Magnus Hagander wrote:\n> >> >\n> >> >\n> >> > On Tue, Sep 8, 2020 at 8:10 AM Amit Kapila <amit.kapila16@gmail.com\n> <mailto:amit.kapila16@gmail.com>> wrote:\n> >> >\n> >> > We use the timestamp of the global statfile if we are not able to\n> >> > determine it for a particular database either because the entry\n> for\n> >> > that database doesn't exist or there is an error while reading the\n> >> > specific database entry. This was not taken care of while reading\n> >> > other entries like ArchiverStats or SLRUStats. See\n> >> > pgstat_read_db_statsfile_timestamp. I have observed this while\n> >> > reviewing Sawada-San's patch related to logical replication stats\n> [1].\n> >> >\n> >> > I think this can only happen if due to some reason the statfile\n> got\n> >> > corrupt or we\n> >> > have some bug in stats writing code, the chances of both are rare\n> and even\n> >> > if that happens we will use stale statistics.\n> >> >\n> >> > The attached patch by Sawada-San will fix this issue. As the\n> chances of this\n> >> > the problem is rare and nobody has reported any issue related to\n> this,\n> >> > so it might be okay not to backpatch this.\n> >> >\n> >> > Thoughts?\n> >> >\n> >> >\n> >> > Why are we reading the archiver statis and and slru stats in\n> \"pgstat_read_db_statsfile_timestamp\" in the first place?\n> >>\n> >> Maybe because they are written before database stats entries? That is,\n> >> to read the target database stats entry and get the timestamp from it,\n> >> we need to read (or lseek) all the global stats entries written before\n> them.\n> >>\n> >\n> > Oh meh. Yeah, I'm reading this thing completely wrong :/ Ignore my\n> comments :)\n> >\n> >\n> >\n> >> > That seems well out of scope for that function.\n> >> >\n> >> > If nothing else the comment at the top of that function is out of\n> touch with reality. We do seem to read it into local buffers and then\n> ignore the contents. I guess we're doing it just to verify that it's not\n> corrupt -- so perhaps the function should actually have a different name\n> than it does now, since it certainly seems to do more than actually read\n> the statsfile timestamp.\n> >> >\n> >> > Specifically in this patch it looks wrong -- in the case of say the\n> SLRU stats being corrupt, we will now return the timestamp of the global\n> stats file even if there is one existing for the database requested, which\n> definitely breaks the contract of the function.\n> >>\n> >> Yes.\n> >> We should return false when fread() for database entry fails, instead?\n> That is,\n> >>\n> >> 1. If corrupted stats file is found, the function always returns false.\n> >> 2. If the file is not currupted and the target database entry is found,\n> its timestamp is returned.\n> >> 3. If the file is not corrupted and the target is NOT found, the\n> timestamp of global entry is returned\n> >\n> >\n> > Yeah, with more coffee and re-reading it, I'm not sure how we could have\n> the database stats being OK if the archiver or slru stats are not.\n> >\n> > That said, I think it still makes sense to return false if the stats\n> file is corrupt. How much can we trust the first block, if the block right\n> after it is corrupt? So yeah, I think your described order seems correct.\n> But that's also what the code already did before this patch, isn't it?\n> >\n>\n> No, before patch as well, if we can't read the DB entry say because\n> the file is corrupt, we return true and use timestamp of global stats\n> file and this is what is established by the original commit 187492b6.\n>\n\nUh, the patch changes:\n- return false;\n+ return true;\n\nIn the \"codepath of corruption\". After also setting the value.\n\nSo AFAICT before the patch, it returns false if the file is corrupt\n(there's a set of such scenarios, all returning false), just after logging\nthat it's corrupt.The patch changes it to log that it's corrupt and then\nreturn true.\n\nThe fact that it doesn't find the database doesn't mean the file is\ncorrupt, it just means the database is inactive. But missing global,\narchiver or slru stats means it's corrupt.\n\n\n\n> So, if we consider that as correct then the functionality is something\n> like once we have read the timestamp of the global statfile, we use\n> that if we can't read the actual db entry for whatever reason. It\n> seems if we return false, the caller will call this function again in\n> the loop. Now, I see the point that if we can't read some part of the\n> file we should return false instead but not sure if that is helpful\n> from the perspective of the caller of\n> pgstat_read_db_statsfile_timestamp.\n>\n\nBut we are not talking about the \"if we can't read the actual db entry\"\ncase, we are talking about the *global* parts of the file.\n\nThough in fact the one inconsistent place in the code now is that if it is\ncorrupt in the db entry part of the file it returns true and the global\ntimestamp, which I would argue is perhaps incorrect and it should return\nfalse.\n\n By returning false in the corrupt case we make the caller sleep and try\nagain, which seems to be the correct thing to do (since the stats collector\nwill be rewriting the file regularly)\n\nI have included Alvaro as he is a committer for 187492b6, so he might\n> remember something and let us know if this is a mistake or there is\n> some reason for doing so (return true even when the db entry we are\n> trying to read is corrupt).\n>\n\nAgain, it looks to me like 187492b6 is doing exactly that -- it returns\nfalse on corrupt file. It returns true if the file is OK, regardless of if\nit finds the database, using the global timestamp if the database is not\nfound.\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, Sep 9, 2020 at 5:04 AM Amit Kapila <amit.kapila16@gmail.com> wrote:On Tue, Sep 8, 2020 at 7:03 PM Magnus Hagander <magnus@hagander.net> wrote:\n>\n> On Tue, Sep 8, 2020 at 3:11 PM Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\n>>\n>>\n>>\n>> On 2020/09/08 19:28, Magnus Hagander wrote:\n>> >\n>> >\n>> > On Tue, Sep 8, 2020 at 8:10 AM Amit Kapila <amit.kapila16@gmail.com <mailto:amit.kapila16@gmail.com>> wrote:\n>> >\n>> >     We use the timestamp of the global statfile if we are not able to\n>> >     determine it for a particular database either because the entry for\n>> >     that database doesn't exist or there is an error while reading the\n>> >     specific database entry. This was not taken care of while reading\n>> >     other entries like ArchiverStats or SLRUStats. See\n>> >     pgstat_read_db_statsfile_timestamp. I have observed this while\n>> >     reviewing Sawada-San's patch related to logical replication stats [1].\n>> >\n>> >     I think this can only happen if due to some reason the statfile got\n>> >     corrupt or we\n>> >     have some bug in stats writing code, the chances of both are rare and even\n>> >     if that happens we will use stale statistics.\n>> >\n>> >     The attached patch by Sawada-San will fix this issue. As the chances of this\n>> >     the problem is rare and nobody has reported any issue related to this,\n>> >     so it might be okay not to backpatch this.\n>> >\n>> >     Thoughts?\n>> >\n>> >\n>> > Why are we reading the archiver statis and and slru stats in \"pgstat_read_db_statsfile_timestamp\" in the first place?\n>>\n>> Maybe because they are written before database stats entries? That is,\n>> to read the target database stats entry and get the timestamp from it,\n>> we need to read (or lseek) all the global stats entries written before them.\n>>\n>\n> Oh meh. Yeah, I'm reading this thing completely wrong :/ Ignore my comments :)\n>\n>\n>\n>> > That seems well out of scope for that function.\n>> >\n>> > If nothing else the comment at the top of that function is out of touch with reality. We do seem to read it into local buffers and then ignore the contents. I guess we're doing it just to verify that it's not corrupt -- so perhaps the function should actually have a different name than it does now, since it certainly seems to do more than actually read the statsfile timestamp.\n>> >\n>> > Specifically in this patch it looks wrong -- in the case of say the SLRU stats being corrupt, we will now return the timestamp of the global stats file even if there is one existing for the database requested, which definitely breaks the contract of the function.\n>>\n>> Yes.\n>> We should return false when fread() for database entry fails, instead? That is,\n>>\n>> 1. If corrupted stats file is found, the function always returns false.\n>> 2. If the file is not currupted and the target database entry is found, its timestamp is returned.\n>> 3. If the file is not corrupted and the target is NOT found, the timestamp of global entry is returned\n>\n>\n> Yeah, with more coffee and re-reading it, I'm not sure how we could have the database stats being OK if the archiver or slru stats are not.\n>\n> That said, I think it still makes sense to return false if the stats file is corrupt. How much can we trust the first block, if the block right after it is corrupt? So yeah, I think your described order seems correct. But that's also what the code already did before this patch, isn't it?\n>\n\nNo, before patch as well, if we can't read the DB entry say because\nthe file is corrupt, we return true and use timestamp of global stats\nfile and this is what is established by the original commit 187492b6.Uh, the patch changes:-       return false;+       return true;In the \"codepath of corruption\". After also setting the value.So AFAICT before the patch, it returns false if the file is corrupt (there's a set  of such scenarios, all returning false), just after logging that it's corrupt.The patch changes it to log that it's corrupt and then return true.The fact that it doesn't find the database doesn't mean the file is corrupt, it just means the database is inactive. But missing global, archiver or slru stats means it's corrupt. \nSo, if we consider that as correct then the functionality is something\nlike once we have read the timestamp of the global statfile, we use\nthat if we can't read the actual db entry for whatever reason. It\nseems if we return false, the caller will call this function again in\nthe loop. Now, I see the point that if we can't read some part of the\nfile we should return false instead but not sure if that is helpful\nfrom the perspective of the caller of\npgstat_read_db_statsfile_timestamp.But we are not talking about the \"if we can't read the actual db entry\" case, we are talking about the *global* parts of the file.Though in fact the one inconsistent place in the code now is that if it is corrupt in the db entry part of the file it returns true and the global timestamp, which I would argue is perhaps incorrect and it should return false. By returning false in the corrupt case we make the caller sleep and try again, which seems to be the correct thing to do (since the stats collector will be rewriting the file regularly)\nI have included Alvaro as he is a committer for 187492b6, so he might\nremember something and let us know if this is a mistake or there is\nsome reason for doing so (return true even when the db entry we are\ntrying to read is corrupt).Again, it looks to me like  187492b6 is doing exactly that -- it returns false on corrupt file. It returns true if the file is OK, regardless of if it finds the database, using the global timestamp if the database is not found.--  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Wed, 9 Sep 2020 11:45:20 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On Wed, Sep 9, 2020 at 9:11 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> On Wed, Sep 9, 2020 at 10:54 AM Fujii Masao <masao.fujii@oss.nttdata.com>\n> wrote:\n> >\n> > On 2020/09/09 12:04, Amit Kapila wrote:\n> > >\n> > > No, before patch as well, if we can't read the DB entry say because\n> > > the file is corrupt, we return true and use timestamp of global stats\n> > > file and this is what is established by the original commit 187492b6.\n> > > So, if we consider that as correct then the functionality is something\n> > > like once we have read the timestamp of the global statfile, we use\n> > > that if we can't read the actual db entry for whatever reason. It\n> > > seems if we return false, the caller will call this function again in\n> > > the loop. Now, I see the point that if we can't read some part of the\n> > > file we should return false instead but not sure if that is helpful\n> > > from the perspective of the caller of\n> > > pgstat_read_db_statsfile_timestamp.\n> >\n> > When false is returned, the caller backend_read_statsfile() seems to\n> > request the stats collector to write a fresh stats data into the file,\n> > and then pgstat_read_db_statsfile_timestamp() can try to read the fresh\n> > file that may not be corrupted. So returning false in that case seems ok\n> > to me...\n> >\n>\n> Hmm, the request to get fresh data is sent irrespective of true or\n> false. We send it to get the latest data if it is not present and it\n>\n\nNo we don't. Just before we request it, there is:\n /* Normal acceptance case: file is not older than cutoff time */\n if (ok && file_ts >= min_ts)\n break;\n\nSo it only requests a new file in the case that it returned false.\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, Sep 9, 2020 at 9:11 AM Amit Kapila <amit.kapila16@gmail.com> wrote:On Wed, Sep 9, 2020 at 10:54 AM Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\n>\n> On 2020/09/09 12:04, Amit Kapila wrote:\n> >\n> > No, before patch as well, if we can't read the DB entry say because\n> > the file is corrupt, we return true and use timestamp of global stats\n> > file and this is what is established by the original commit 187492b6.\n> > So, if we consider that as correct then the functionality is something\n> > like once we have read the timestamp of the global statfile, we use\n> > that if we can't read the actual db entry for whatever reason. It\n> > seems if we return false, the caller will call this function again in\n> > the loop. Now, I see the point that if we can't read some part of the\n> > file we should return false instead but not sure if that is helpful\n> > from the perspective of the caller of\n> > pgstat_read_db_statsfile_timestamp.\n>\n> When false is returned, the caller backend_read_statsfile() seems to\n> request the stats collector to write a fresh stats data into the file,\n> and then pgstat_read_db_statsfile_timestamp() can try to read the fresh\n> file that may not be corrupted. So returning false in that case seems ok\n> to me...\n>\n\nHmm, the request to get fresh data is sent irrespective of true or\nfalse. We send it to get the latest data if it is not present and itNo we don't. Just before we request it, there is:        /* Normal acceptance case: file is not older than cutoff time */        if (ok && file_ts >= min_ts)            break;So it only requests a new file in the case that it returned false.--  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Wed, 9 Sep 2020 11:46:56 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On Wed, Sep 9, 2020 at 3:15 PM Magnus Hagander <magnus@hagander.net> wrote:\n>\n> On Wed, Sep 9, 2020 at 5:04 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>>\n>\n> Though in fact the one inconsistent place in the code now is that if it is corrupt in the db entry part of the file it returns true and the global timestamp, which I would argue is perhaps incorrect and it should return false.\n>\n\nYeah, this is exactly the case I was pointing out where we return true\nbefore the patch, basically the code below:\ncase 'D':\nif (fread(&dbentry, 1, offsetof(PgStat_StatDBEntry, tables),\n fpin) != offsetof(PgStat_StatDBEntry, tables))\n{\nereport(pgStatRunningInCollector ? LOG : WARNING,\n(errmsg(\"corrupted statistics file \\\"%s\\\"\",\nstatfile)));\ngoto done;\n}\n\ndone:\nFreeFile(fpin);\nreturn true;\n\nNow, if we decide to return 'false' here, then surely there is no\nargument and we should return false in other cases as well. Basically,\nI think we should be consistent in handling the corrupt file case.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Wed, 9 Sep 2020 15:53:40 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On Wed, Sep 9, 2020 at 3:17 PM Magnus Hagander <magnus@hagander.net> wrote:\n>\n> On Wed, Sep 9, 2020 at 9:11 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>>\n>> On Wed, Sep 9, 2020 at 10:54 AM Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\n>> >\n>> > On 2020/09/09 12:04, Amit Kapila wrote:\n>> > >\n>> > > No, before patch as well, if we can't read the DB entry say because\n>> > > the file is corrupt, we return true and use timestamp of global stats\n>> > > file and this is what is established by the original commit 187492b6.\n>> > > So, if we consider that as correct then the functionality is something\n>> > > like once we have read the timestamp of the global statfile, we use\n>> > > that if we can't read the actual db entry for whatever reason. It\n>> > > seems if we return false, the caller will call this function again in\n>> > > the loop. Now, I see the point that if we can't read some part of the\n>> > > file we should return false instead but not sure if that is helpful\n>> > > from the perspective of the caller of\n>> > > pgstat_read_db_statsfile_timestamp.\n>> >\n>> > When false is returned, the caller backend_read_statsfile() seems to\n>> > request the stats collector to write a fresh stats data into the file,\n>> > and then pgstat_read_db_statsfile_timestamp() can try to read the fresh\n>> > file that may not be corrupted. So returning false in that case seems ok\n>> > to me...\n>> >\n>>\n>> Hmm, the request to get fresh data is sent irrespective of true or\n>> false. We send it to get the latest data if it is not present and it\n>\n>\n> No we don't. Just before we request it, there is:\n> /* Normal acceptance case: file is not older than cutoff time */\n> if (ok && file_ts >= min_ts)\n> break;\n>\n> So it only requests a new file in the case that it returned false.\n>\n\nWhat if the second part of the above 'if' statement is false, then\nbasically even when pgstat_read_db_statsfile_timestamp() has returned\ntrue, we can send a request. IIUC, here the basic idea is if the stats\nin the file is updated before cut_off time, then we do send the\nrequest and wait for updated stats.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Wed, 9 Sep 2020 15:56:51 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On Wed, Sep 09, 2020 at 03:53:40PM +0530, Amit Kapila wrote:\n>On Wed, Sep 9, 2020 at 3:15 PM Magnus Hagander <magnus@hagander.net> wrote:\n>>\n>> On Wed, Sep 9, 2020 at 5:04 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>>>\n>>\n>> Though in fact the one inconsistent place in the code now is that if it is corrupt in the db entry part of the file it returns true and the global timestamp, which I would argue is perhaps incorrect and it should return false.\n>>\n>\n>Yeah, this is exactly the case I was pointing out where we return true\n>before the patch, basically the code below:\n>case 'D':\n>if (fread(&dbentry, 1, offsetof(PgStat_StatDBEntry, tables),\n> fpin) != offsetof(PgStat_StatDBEntry, tables))\n>{\n>ereport(pgStatRunningInCollector ? LOG : WARNING,\n>(errmsg(\"corrupted statistics file \\\"%s\\\"\",\n>statfile)));\n>goto done;\n>}\n>\n>done:\n>FreeFile(fpin);\n>return true;\n>\n>Now, if we decide to return 'false' here, then surely there is no\n>argument and we should return false in other cases as well. Basically,\n>I think we should be consistent in handling the corrupt file case.\n>\n\nFWIW I do agree with this - we should return false here, to make it\nreturn false like in the other data corruption cases. AFAICS that's the\nonly inconsistency here.\n\n\nregards\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 9 Sep 2020 15:56:42 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On Wed, Sep 9, 2020 at 3:56 PM Tomas Vondra <tomas.vondra@2ndquadrant.com>\nwrote:\n\n> On Wed, Sep 09, 2020 at 03:53:40PM +0530, Amit Kapila wrote:\n> >On Wed, Sep 9, 2020 at 3:15 PM Magnus Hagander <magnus@hagander.net>\n> wrote:\n> >>\n> >> On Wed, Sep 9, 2020 at 5:04 AM Amit Kapila <amit.kapila16@gmail.com>\n> wrote:\n> >>>\n> >>\n> >> Though in fact the one inconsistent place in the code now is that if it\n> is corrupt in the db entry part of the file it returns true and the global\n> timestamp, which I would argue is perhaps incorrect and it should return\n> false.\n> >>\n> >\n> >Yeah, this is exactly the case I was pointing out where we return true\n> >before the patch, basically the code below:\n> >case 'D':\n> >if (fread(&dbentry, 1, offsetof(PgStat_StatDBEntry, tables),\n> > fpin) != offsetof(PgStat_StatDBEntry, tables))\n> >{\n> >ereport(pgStatRunningInCollector ? LOG : WARNING,\n> >(errmsg(\"corrupted statistics file \\\"%s\\\"\",\n> >statfile)));\n> >goto done;\n> >}\n> >\n> >done:\n> >FreeFile(fpin);\n> >return true;\n> >\n> >Now, if we decide to return 'false' here, then surely there is no\n> >argument and we should return false in other cases as well. Basically,\n> >I think we should be consistent in handling the corrupt file case.\n> >\n>\n> FWIW I do agree with this - we should return false here, to make it\n> return false like in the other data corruption cases. AFAICS that's the\n> only inconsistency here.\n>\n\n+1, I think that's the place to fix, rather than reversing all the other\nplaces.\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, Sep 9, 2020 at 3:56 PM Tomas Vondra <tomas.vondra@2ndquadrant.com> wrote:On Wed, Sep 09, 2020 at 03:53:40PM +0530, Amit Kapila wrote:\n>On Wed, Sep 9, 2020 at 3:15 PM Magnus Hagander <magnus@hagander.net> wrote:\n>>\n>> On Wed, Sep 9, 2020 at 5:04 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>>>\n>>\n>> Though in fact the one inconsistent place in the code now is that if it is corrupt in the db entry part of the file it returns true and the global timestamp, which I would argue is perhaps incorrect and it should return false.\n>>\n>\n>Yeah, this is exactly the case I was pointing out where we return true\n>before the patch, basically the code below:\n>case 'D':\n>if (fread(&dbentry, 1, offsetof(PgStat_StatDBEntry, tables),\n>  fpin) != offsetof(PgStat_StatDBEntry, tables))\n>{\n>ereport(pgStatRunningInCollector ? LOG : WARNING,\n>(errmsg(\"corrupted statistics file \\\"%s\\\"\",\n>statfile)));\n>goto done;\n>}\n>\n>done:\n>FreeFile(fpin);\n>return true;\n>\n>Now, if we decide to return 'false' here, then surely there is no\n>argument and we should return false in other cases as well. Basically,\n>I think we should be consistent in handling the corrupt file case.\n>\n\nFWIW I do agree with this - we should return false here, to make it\nreturn false like in the other data corruption cases. AFAICS that's the\nonly inconsistency here.+1, I think that's the place to fix, rather than reversing all the other places. --  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Wed, 9 Sep 2020 15:57:36 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On 2020-Sep-09, Amit Kapila wrote:\n\n> I have included Alvaro as he is a committer for 187492b6, so he might\n> remember something and let us know if this is a mistake or there is\n> some reason for doing so (return true even when the db entry we are\n> trying to read is corrupt).\n\nThanks -- I have to excuse myself here, as I don't have too many\nmemories about this. It seems y'all have derived more insight that I\ncould possibly offer.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 9 Sep 2020 13:01:26 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "\n\nOn 2020/09/09 22:57, Magnus Hagander wrote:\n> On Wed, Sep 9, 2020 at 3:56 PM Tomas Vondra <tomas.vondra@2ndquadrant.com <mailto:tomas.vondra@2ndquadrant.com>> wrote:\n> \n> On Wed, Sep 09, 2020 at 03:53:40PM +0530, Amit Kapila wrote:\n> >On Wed, Sep 9, 2020 at 3:15 PM Magnus Hagander <magnus@hagander.net <mailto:magnus@hagander.net>> wrote:\n> >>\n> >> On Wed, Sep 9, 2020 at 5:04 AM Amit Kapila <amit.kapila16@gmail.com <mailto:amit.kapila16@gmail.com>> wrote:\n> >>>\n> >>\n> >> Though in fact the one inconsistent place in the code now is that if it is corrupt in the db entry part of the file it returns true and the global timestamp, which I would argue is perhaps incorrect and it should return false.\n> >>\n> >\n> >Yeah, this is exactly the case I was pointing out where we return true\n> >before the patch, basically the code below:\n> >case 'D':\n> >if (fread(&dbentry, 1, offsetof(PgStat_StatDBEntry, tables),\n> >  fpin) != offsetof(PgStat_StatDBEntry, tables))\n> >{\n> >ereport(pgStatRunningInCollector ? LOG : WARNING,\n> >(errmsg(\"corrupted statistics file \\\"%s\\\"\",\n> >statfile)));\n> >goto done;\n> >}\n> >\n> >done:\n> >FreeFile(fpin);\n> >return true;\n> >\n> >Now, if we decide to return 'false' here, then surely there is no\n> >argument and we should return false in other cases as well. Basically,\n> >I think we should be consistent in handling the corrupt file case.\n> >\n> \n> FWIW I do agree with this - we should return false here, to make it\n> return false like in the other data corruption cases. AFAICS that's the\n> only inconsistency here.\n> \n> \n> +1, I think that's the place to fix, rather than reversing all the other places.\n\n+1 as I suggested upthread!\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 10 Sep 2020 01:07:40 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On Wed, Sep 9, 2020 at 9:37 PM Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\n>\n> On 2020/09/09 22:57, Magnus Hagander wrote:\n> > On Wed, Sep 9, 2020 at 3:56 PM Tomas Vondra <tomas.vondra@2ndquadrant.com <mailto:tomas.vondra@2ndquadrant.com>> wrote:\n> >\n> > On Wed, Sep 09, 2020 at 03:53:40PM +0530, Amit Kapila wrote:\n> > >On Wed, Sep 9, 2020 at 3:15 PM Magnus Hagander <magnus@hagander.net <mailto:magnus@hagander.net>> wrote:\n> > >>\n> > >> On Wed, Sep 9, 2020 at 5:04 AM Amit Kapila <amit.kapila16@gmail.com <mailto:amit.kapila16@gmail.com>> wrote:\n> > >>>\n> > >>\n> > >> Though in fact the one inconsistent place in the code now is that if it is corrupt in the db entry part of the file it returns true and the global timestamp, which I would argue is perhaps incorrect and it should return false.\n> > >>\n> > >\n> > >Yeah, this is exactly the case I was pointing out where we return true\n> > >before the patch, basically the code below:\n> > >case 'D':\n> > >if (fread(&dbentry, 1, offsetof(PgStat_StatDBEntry, tables),\n> > > fpin) != offsetof(PgStat_StatDBEntry, tables))\n> > >{\n> > >ereport(pgStatRunningInCollector ? LOG : WARNING,\n> > >(errmsg(\"corrupted statistics file \\\"%s\\\"\",\n> > >statfile)));\n> > >goto done;\n> > >}\n> > >\n> > >done:\n> > >FreeFile(fpin);\n> > >return true;\n> > >\n> > >Now, if we decide to return 'false' here, then surely there is no\n> > >argument and we should return false in other cases as well. Basically,\n> > >I think we should be consistent in handling the corrupt file case.\n> > >\n> >\n> > FWIW I do agree with this - we should return false here, to make it\n> > return false like in the other data corruption cases. AFAICS that's the\n> > only inconsistency here.\n> >\n> >\n> > +1, I think that's the place to fix, rather than reversing all the other places.\n>\n> +1 as I suggested upthread!\n>\n\nPlease find the patch attached based on the above discussion. I have\nslightly adjusted the comments.\n\n-- \nWith Regards,\nAmit Kapila.", "msg_date": "Thu, 10 Sep 2020 10:54:30 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On Thu, 10 Sep 2020 at 14:24, Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Wed, Sep 9, 2020 at 9:37 PM Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\n> >\n> > On 2020/09/09 22:57, Magnus Hagander wrote:\n> > > On Wed, Sep 9, 2020 at 3:56 PM Tomas Vondra <tomas.vondra@2ndquadrant.com <mailto:tomas.vondra@2ndquadrant.com>> wrote:\n> > >\n> > > On Wed, Sep 09, 2020 at 03:53:40PM +0530, Amit Kapila wrote:\n> > > >On Wed, Sep 9, 2020 at 3:15 PM Magnus Hagander <magnus@hagander.net <mailto:magnus@hagander.net>> wrote:\n> > > >>\n> > > >> On Wed, Sep 9, 2020 at 5:04 AM Amit Kapila <amit.kapila16@gmail.com <mailto:amit.kapila16@gmail.com>> wrote:\n> > > >>>\n> > > >>\n> > > >> Though in fact the one inconsistent place in the code now is that if it is corrupt in the db entry part of the file it returns true and the global timestamp, which I would argue is perhaps incorrect and it should return false.\n> > > >>\n> > > >\n> > > >Yeah, this is exactly the case I was pointing out where we return true\n> > > >before the patch, basically the code below:\n> > > >case 'D':\n> > > >if (fread(&dbentry, 1, offsetof(PgStat_StatDBEntry, tables),\n> > > > fpin) != offsetof(PgStat_StatDBEntry, tables))\n> > > >{\n> > > >ereport(pgStatRunningInCollector ? LOG : WARNING,\n> > > >(errmsg(\"corrupted statistics file \\\"%s\\\"\",\n> > > >statfile)));\n> > > >goto done;\n> > > >}\n> > > >\n> > > >done:\n> > > >FreeFile(fpin);\n> > > >return true;\n> > > >\n> > > >Now, if we decide to return 'false' here, then surely there is no\n> > > >argument and we should return false in other cases as well. Basically,\n> > > >I think we should be consistent in handling the corrupt file case.\n> > > >\n> > >\n> > > FWIW I do agree with this - we should return false here, to make it\n> > > return false like in the other data corruption cases. AFAICS that's the\n> > > only inconsistency here.\n> > >\n> > >\n> > > +1, I think that's the place to fix, rather than reversing all the other places.\n> >\n> > +1 as I suggested upthread!\n> >\n>\n> Please find the patch attached based on the above discussion. I have\n> slightly adjusted the comments.\n\nFWIW reading the discussion, I also agree to fix it to return false in\ncase of file corruption.\n\nRegarding the v2 patch, I think we should return false in the\nfollowing case too:\n\n default:\n ereport(pgStatRunningInCollector ? LOG : WARNING,\n (errmsg(\"corrupted statistics file \\\"%s\\\"\",\n statfile)));\n goto done;\n\nRegards,\n\n-- \nMasahiko Sawada http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 10 Sep 2020 15:21:41 +0900", "msg_from": "Masahiko Sawada <masahiko.sawada@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On Thu, Sep 10, 2020 at 11:52 AM Masahiko Sawada\n<masahiko.sawada@2ndquadrant.com> wrote:\n>\n>\n> Regarding the v2 patch, I think we should return false in the\n> following case too:\n>\n> default:\n> ereport(pgStatRunningInCollector ? LOG : WARNING,\n> (errmsg(\"corrupted statistics file \\\"%s\\\"\",\n> statfile)));\n> goto done;\n>\n\nmakes sense, attached find the updated patch.\n\n-- \nWith Regards,\nAmit Kapila.", "msg_date": "Thu, 10 Sep 2020 12:35:01 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On Thu, Sep 10, 2020 at 9:05 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> On Thu, Sep 10, 2020 at 11:52 AM Masahiko Sawada\n> <masahiko.sawada@2ndquadrant.com> wrote:\n> >\n> >\n> > Regarding the v2 patch, I think we should return false in the\n> > following case too:\n> >\n> > default:\n> > ereport(pgStatRunningInCollector ? LOG : WARNING,\n> > (errmsg(\"corrupted statistics file \\\"%s\\\"\",\n> > statfile)));\n> > goto done;\n> >\n>\n> makes sense, attached find the updated patch.\n>\n\nAs a minor nitpick, technically, I think the comment change is wrong,\nbecause it says that the caller *must* rely on the timestamp, which it of\ncourse doesn't. I think a more proper one is \"The caller must not rely on\nthe timestamp in case the function returns false\" or \"The caller must only\nrely on the timestamp if the function returns true\".\n\n+1 on the code parts.\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 Thu, Sep 10, 2020 at 9:05 AM Amit Kapila <amit.kapila16@gmail.com> wrote:On Thu, Sep 10, 2020 at 11:52 AM Masahiko Sawada\n<masahiko.sawada@2ndquadrant.com> wrote:\n>\n>\n> Regarding the v2 patch, I think we should return false in the\n> following case too:\n>\n>             default:\n>                 ereport(pgStatRunningInCollector ? LOG : WARNING,\n>                         (errmsg(\"corrupted statistics file \\\"%s\\\"\",\n>                                 statfile)));\n>                 goto done;\n>\n\nmakes sense, attached find the updated patch.As a minor nitpick, technically, I think the comment change is wrong, because it says that the caller *must* rely on the timestamp, which it of course doesn't. I think a more proper one is \"The caller must not rely on the timestamp in case the function returns false\" or \"The caller must only rely on the timestamp if the function returns true\".+1 on the code parts.--  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Thu, 10 Sep 2020 09:33:43 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On Thu, Sep 10, 2020 at 1:03 PM Magnus Hagander <magnus@hagander.net> wrote:\n>\n> On Thu, Sep 10, 2020 at 9:05 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>>\n>> On Thu, Sep 10, 2020 at 11:52 AM Masahiko Sawada\n>> <masahiko.sawada@2ndquadrant.com> wrote:\n>> >\n>> >\n>> > Regarding the v2 patch, I think we should return false in the\n>> > following case too:\n>> >\n>> > default:\n>> > ereport(pgStatRunningInCollector ? LOG : WARNING,\n>> > (errmsg(\"corrupted statistics file \\\"%s\\\"\",\n>> > statfile)));\n>> > goto done;\n>> >\n>>\n>> makes sense, attached find the updated patch.\n>\n>\n> As a minor nitpick, technically, I think the comment change is wrong, because it says that the caller *must* rely on the timestamp, which it of course doesn't. I think a more proper one is \"The caller must not rely on the timestamp in case the function returns false\" or \"The caller must only rely on the timestamp if the function returns true\".\n>\n\nThe comments already say what you said in the second suggestion:\"The\ncaller must rely on timestamp stored in *ts iff the function returns\ntrue.\". Read iff \"as if and only if\"\n\n> +1 on the code parts.\n>\n\nBTW, do we want to backpatch this? There is no user reported bug and\nnot sure if the user will encounter any problem. I think it is a minor\nimprovement and more of code consistency. So, making HEAD only change\nshould be okay.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Thu, 10 Sep 2020 13:13:18 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On 2020-Sep-10, Amit Kapila wrote:\n\n> On Thu, Sep 10, 2020 at 1:03 PM Magnus Hagander <magnus@hagander.net> wrote:\n\n> The comments already say what you said in the second suggestion:\"The\n> caller must rely on timestamp stored in *ts iff the function returns\n> true.\". Read iff \"as if and only if\"\n\nI think \"must\" should be \"may\" there, if we're nitpicking.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 10 Sep 2020 10:12:10 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On Thu, Sep 10, 2020 at 6:42 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n>\n> On 2020-Sep-10, Amit Kapila wrote:\n>\n> > On Thu, Sep 10, 2020 at 1:03 PM Magnus Hagander <magnus@hagander.net> wrote:\n>\n> > The comments already say what you said in the second suggestion:\"The\n> > caller must rely on timestamp stored in *ts iff the function returns\n> > true.\". Read iff \"as if and only if\"\n>\n> I think \"must\" should be \"may\" there, if we're nitpicking.\n>\n\nHere, we want to say that \"caller can rely on *ts only if the function\nreturns true\". If we replace 'must' with 'may' then it seems to me we\nare trying to say that caller can ignore the timestamp value, if so,\nwhy at first place caller has called this function.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Fri, 11 Sep 2020 08:22:56 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On Thu, Sep 10, 2020 at 1:13 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n>\n> BTW, do we want to backpatch this? There is no user reported bug and\n> not sure if the user will encounter any problem. I think it is a minor\n> improvement and more of code consistency. So, making HEAD only change\n> should be okay.\n>\n\nSeeing no other opinions, pushed this in Head.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Sat, 12 Sep 2020 17:19:24 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." }, { "msg_contents": "On Fri, Sep 11, 2020 at 4:53 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> On Thu, Sep 10, 2020 at 6:42 PM Alvaro Herrera <alvherre@2ndquadrant.com>\n> wrote:\n> >\n> > On 2020-Sep-10, Amit Kapila wrote:\n> >\n> > > On Thu, Sep 10, 2020 at 1:03 PM Magnus Hagander <magnus@hagander.net>\n> wrote:\n> >\n> > > The comments already say what you said in the second suggestion:\"The\n> > > caller must rely on timestamp stored in *ts iff the function returns\n> > > true.\". Read iff \"as if and only if\"\n> >\n> > I think \"must\" should be \"may\" there, if we're nitpicking.\n> >\n>\n> Here, we want to say that \"caller can rely on *ts only if the function\n> returns true\". If we replace 'must' with 'may' then it seems to me we\n> are trying to say that caller can ignore the timestamp value, if so,\n> why at first place caller has called this function.\n>\n\nThis is true, but that should really be the decision of the caller, not of\nthe function.\n\nBut again, that's extremely nitpicky, so it doesn't really matter :)\n\nAnd +1 on the push you did, and the decision not to backpatch it since\nthere haven't been any reports.\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, Sep 11, 2020 at 4:53 AM Amit Kapila <amit.kapila16@gmail.com> wrote:On Thu, Sep 10, 2020 at 6:42 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n>\n> On 2020-Sep-10, Amit Kapila wrote:\n>\n> > On Thu, Sep 10, 2020 at 1:03 PM Magnus Hagander <magnus@hagander.net> wrote:\n>\n> > The comments already say what you said in the second suggestion:\"The\n> > caller must rely on timestamp stored in *ts iff the function returns\n> > true.\". Read iff \"as if and only if\"\n>\n> I think \"must\" should be \"may\" there, if we're nitpicking.\n>\n\nHere, we want to say that \"caller can rely on *ts only if the function\nreturns true\". If we replace 'must' with 'may' then it seems to me we\nare trying to say that caller can ignore the timestamp value, if so,\nwhy at first place caller has called this function.This is true, but that should really be the decision of the caller, not of the function. But again, that's extremely nitpicky, so it doesn't really matter :)And +1 on the push you did, and the decision not to backpatch it since there haven't been any reports.--  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Sat, 12 Sep 2020 15:17:58 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: Inconsistency in determining the timestamp of the db statfile." } ]
[ { "msg_contents": "While running a simple SELECT statement on a table where I expected\nindexonly scan to be preferred over sequential scan, the planner kept on\nselecting the sequential scan. Looking at the EXPLAIN output, it seemed\nobvious that the cost of indexonly was exceeding that of sequential scan.\nSo the planner was right, however, my expectation was that indexonly should\nhave been selected instead.\n\nFollowing is an example table that I’ll be referring to.\n\n-- Creating a very basic table, index and running vacuum analyze\nCREATE TABLE index_test AS (SELECT GENERATE_SERIES(1, 10000000)::int id,\n'hello world' AS name);\nCREATE INDEX on index_test;\nVACUUM ANALYZE index_test;\n\n-- SELECT statement\nSELECT id FROM index_test WHERE id < [SOME VALUE];\n\nSo as a starting point, I wanted to identify when the cost for indexonly\nexceeds that of a sequential scan. In my case, the number turned out to be\n6,243,354 with the table containing 10,000,000 tuples.\n\nWhen the cost exceeds, the planner should select the more optimum path.\nHowever, my concern was why is the indexonly scan cost greater than that of\nsequential one. Turning on the timing, the expectation was that at the\ntipping point, indexonly execution time should be greater than that of\nsequential one. However, I see that indexonly scan’s execution was much\nmuch faster than the sequential scan. In terms of timing, this is what I\nexpected. So I turned on the timing in psql and ran EXPLAIN ANALYZE.\nFollowing are the outputs.\n\n-- SEQUENTIAL SCAN\nEXPLAIN ANALYZE SELECT id FROM index_test WHERE id < 6243354;\n\n QUERY PLAN\n\n-----------------------------------------------------------------------------------------------------------------------\n Seq Scan on index_test (cost=0.00..179053.25 rows=6227030 width=4)\n(actual time=0.175..993.291 rows=6243353 loops=1)\n Filter: (id < 6243354)\n Rows Removed by Filter: 3756647\n Planning Time: 0.235 ms\n Execution Time: 1149.590 ms\n(5 rows)\n\nTime: 1150.798 ms (00:01.151)\npostgres=# explain analyze select id from index_test where id < 6243353;\n\n\n-- INDEXONLY SCAN\nEXPLAIN ANALYZE SELECT id FROM index_test WHERE id < 6243353;\n\n QUERY\nPLAN\n------------------------------------------------------------------------------------------------------------------------------------------------------\n Index Only Scan using index_test_id_idx on index_test\n (cost=0.43..177277.44 rows=6227029 width=4) (actual time=0.063..718.390\nrows=6243352 loops=1)\n Index Cond: (id < 6243353)\n Heap Fetches: 0\n Planning Time: 0.174 ms\n Execution Time: 873.070 ms\n(5 rows)\n\nTime: 874.079 ms\n\nGiven that this is a very well packed table, still you can see that the\nexecution time increases from 718ms for indexonly scan to 993ms only with\nan increase of a single tuple just because the cost of indexonly scan goes\nbeyond that of sequential scan.\n\nI’ve tried this in a docker, my laptop and on a server without\nvirtualization. All have shown similar gains.\n\nReviewing the costestimate function in cost_size.c, I see that the cost of\nindexonly differs for min_IO_cost and max_IO_cost. The indexTotalCost cost\nremains the same whether it’s an indexonly scan or not. I believe that\ntotal index cost in case of indexonly scan should also be updated.\n\nI don't think there is a need to modify all amcostestimate functions for\nindexes, however, perhaps we can pull in another factor that helps make\ncost for indexonly more realistic.\n\nISTM, it should be reduced by a factor somewhere around (index\nsize)/(relation size), even perhaps putting together expected index size,\nactual index size and relation size in some equation.\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\nWhile running a simple SELECT statement on a table where I expected indexonly scan to be preferred over sequential scan, the planner kept on selecting the sequential scan. Looking at the EXPLAIN output, it seemed obvious that the cost of indexonly was exceeding that of sequential scan. So the planner was right, however, my expectation was that indexonly should have been selected instead.Following is an example table that I’ll be referring to.-- Creating a very basic table, index and running vacuum analyzeCREATE TABLE index_test AS (SELECT GENERATE_SERIES(1, 10000000)::int id, 'hello world' AS name);CREATE INDEX on index_test;VACUUM ANALYZE index_test;-- SELECT statementSELECT id FROM index_test WHERE id < [SOME VALUE];So as a starting point, I wanted to identify when the cost for indexonly exceeds that of a sequential scan. In my case, the number turned out to be 6,243,354 with the table containing 10,000,000 tuples.When the cost exceeds, the planner should select the more optimum path. However, my concern was why is the indexonly scan cost greater than that of sequential one. Turning on the timing, the expectation was that at the tipping point, indexonly execution time should be greater than that of sequential one. However, I see that indexonly scan’s execution was much much faster than the sequential scan. In terms of timing, this is what I expected. So I turned on the timing in psql and ran EXPLAIN ANALYZE. Following are the outputs.-- SEQUENTIAL SCANEXPLAIN ANALYZE SELECT id FROM index_test WHERE id < 6243354;                                                      QUERY PLAN                                                       ----------------------------------------------------------------------------------------------------------------------- Seq Scan on index_test  (cost=0.00..179053.25 rows=6227030 width=4) (actual time=0.175..993.291 rows=6243353 loops=1)   Filter: (id < 6243354)   Rows Removed by Filter: 3756647 Planning Time: 0.235 ms Execution Time: 1149.590 ms(5 rows)Time: 1150.798 ms (00:01.151)postgres=# explain analyze select id from index_test where id < 6243353;-- INDEXONLY SCANEXPLAIN ANALYZE SELECT id FROM index_test WHERE id < 6243353;                                                                      QUERY PLAN                                                                      ------------------------------------------------------------------------------------------------------------------------------------------------------ Index Only Scan using index_test_id_idx on index_test  (cost=0.43..177277.44 rows=6227029 width=4) (actual time=0.063..718.390 rows=6243352 loops=1)   Index Cond: (id < 6243353)   Heap Fetches: 0 Planning Time: 0.174 ms Execution Time: 873.070 ms(5 rows)Time: 874.079 msGiven that this is a very well packed table, still you can see that the execution time increases from 718ms for indexonly scan to 993ms only with an increase of a single tuple just because the cost of indexonly scan goes beyond that of sequential scan.I’ve tried this in a docker, my laptop and on a server without virtualization. All have shown similar gains.Reviewing the costestimate function in cost_size.c, I see that the cost of indexonly differs for min_IO_cost and max_IO_cost. The indexTotalCost cost remains the same whether it’s an indexonly scan or not. I believe that total index cost in case of indexonly scan should also be updated.I don't think there is a need to modify all amcostestimate functions for indexes, however, perhaps we can pull in another factor that helps make cost for indexonly more realistic. ISTM, it should be reduced by a factor somewhere around (index size)/(relation size), even perhaps putting together expected index size, actual index size and relation size in some equation.-- Highgo Software (Canada/China/Pakistan)URL : www.highgo.caADDR: 10318 WHALLEY BLVD, Surrey, BCCELL:+923335449950  EMAIL: mailto:hamid.akhtar@highgo.caSKYPE: engineeredvirus", "msg_date": "Tue, 8 Sep 2020 17:25:43 +0500", "msg_from": "Hamid Akhtar <hamid.akhtar@gmail.com>", "msg_from_op": true, "msg_subject": "Case for Improved Costing for Index Only Scans?" } ]
[ { "msg_contents": "Hi, I ran across a small (but annoying) bug in initializing parallel BTree scans, which causes the parallel-scan state machine to get confused. The fix is one line; the description is a bit longer—\r\n\r\nBefore, function _bt_first() would exit immediately if the specified scan keys could never be satisfied--without notifying other parallel workers, if any, that the scan key was done. This moved that particular worker to a scan key beyond what was in the shared parallel-query state, so that it would later try to read in \"InvalidBlockNumber\", without recognizing it as a special sentinel value.\r\n\r\nThe basic bug is that the BTree parallel query state machine assumes that a worker process is working on a key <= the global key--a worker process can be behind (i.e., hasn't finished its work on a previous key), but never ahead. By allowing the first worker to move on to the next scan key, in this one case, without notifying other workers, the global key ends up < the first worker's local key.\r\n\r\nSymptoms of the bug are: on R/O, we get an error saying we can't extend the index relation, while on an R/W we just extend the index relation by 1 block.\r\n\r\nTo reproduce, you need a query that:\r\n\r\n1. Executes parallel BTree index scan;\r\n2. Has an IN-list of size > 1;\r\n3. Has an additional index filter that makes it impossible to satisfy the\r\n first IN-list condition.\r\n\r\n(We encountered such a query, and therefore the bug, on a production instance.)\r\n\r\nThanks,\r\nJames\r\n\r\n--\r\nJames Hunter, Amazon Web Services (AWS)", "msg_date": "Tue, 8 Sep 2020 18:25:03 +0000", "msg_from": "\"Jameson, Hunter 'James'\" <hunjmes@amazon.com>", "msg_from_op": true, "msg_subject": "Fix for parallel BTree initialization bug" }, { "msg_contents": "On Tue, Sep 8, 2020 at 11:55 PM Jameson, Hunter 'James'\n<hunjmes@amazon.com> wrote:\n>\n> Hi, I ran across a small (but annoying) bug in initializing parallel BTree scans, which causes the parallel-scan state machine to get confused.\n>\n>\n> To reproduce, you need a query that:\n>\n>\n>\n> 1. Executes parallel BTree index scan;\n>\n> 2. Has an IN-list of size > 1;\n>\n> 3. Has an additional index filter that makes it impossible to satisfy the\n>\n> first IN-list condition.\n>\n>\n>\n> (We encountered such a query, and therefore the bug, on a production instance.)\n>\n>\n\nI think I can understand what you are pointing out here but it would\nbe great if you can have a reproducible test case because that will\nmake it apparent and we might want to include that in the regression\ntests if possible.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Wed, 9 Sep 2020 18:44:08 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Fix for parallel BTree initialization bug" }, { "msg_contents": "Hi, I spent some time trying to create a repro (other than testing it on the production instance where we encountered the bug), but was unable to create one within a reasonable time.\r\n\r\nThe tricky part is that the bug symptoms are run-time symptoms -- so not only do you need, first, to satisfy conditions (1), (2), and (3), without the query optimizer optimizing them away! -- but you also need, second, a query that runs long enough for one or more of the parallel workers' state machines to get confused. (This wasn't a problem on the production instance where we encountered the bug and I tested the fix.)\r\n\r\nAlso, third-- passing InvalidBlockNumber to ReadBuffer() generally just appends a new block to the relation, so the bug doesn't even result in an error condition on an RW instance. (The production instance was RO...) So the bug, although very small!, is annoying!\r\n\r\nJames\r\n\r\nOn 9/9/20, 6:14 AM, \"Amit Kapila\" <amit.kapila16@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, Sep 8, 2020 at 11:55 PM Jameson, Hunter 'James'\r\n <hunjmes@amazon.com> wrote:\r\n >\r\n > Hi, I ran across a small (but annoying) bug in initializing parallel BTree scans, which causes the parallel-scan state machine to get confused.\r\n >\r\n >\r\n > To reproduce, you need a query that:\r\n >\r\n >\r\n >\r\n > 1. Executes parallel BTree index scan;\r\n >\r\n > 2. Has an IN-list of size > 1;\r\n >\r\n > 3. Has an additional index filter that makes it impossible to satisfy the\r\n >\r\n > first IN-list condition.\r\n >\r\n >\r\n >\r\n > (We encountered such a query, and therefore the bug, on a production instance.)\r\n >\r\n >\r\n\r\n I think I can understand what you are pointing out here but it would\r\n be great if you can have a reproducible test case because that will\r\n make it apparent and we might want to include that in the regression\r\n tests if possible.\r\n\r\n --\r\n With Regards,\r\n Amit Kapila.\r\n\r\n", "msg_date": "Wed, 9 Sep 2020 14:08:43 +0000", "msg_from": "\"Jameson, Hunter 'James'\" <hunjmes@amazon.com>", "msg_from_op": true, "msg_subject": "Re: Fix for parallel BTree initialization bug" }, { "msg_contents": "On Tue, Sep 08, 2020 at 06:25:03PM +0000, Jameson, Hunter 'James' wrote:\n> Hi, I ran across a small (but annoying) bug in initializing parallel BTree scans, which causes the parallel-scan state machine to get confused. The fix is one line; the description is a bit longer—\n\nWhat postgres version was this ?\n\n> Before, function _bt_first() would exit immediately if the specified scan keys could never be satisfied--without notifying other parallel workers, if any, that the scan key was done. This moved that particular worker to a scan key beyond what was in the shared parallel-query state, so that it would later try to read in \"InvalidBlockNumber\", without recognizing it as a special sentinel value.\n> \n> The basic bug is that the BTree parallel query state machine assumes that a worker process is working on a key <= the global key--a worker process can be behind (i.e., hasn't finished its work on a previous key), but never ahead. By allowing the first worker to move on to the next scan key, in this one case, without notifying other workers, the global key ends up < the first worker's local key.\n> \n> Symptoms of the bug are: on R/O, we get an error saying we can't extend the index relation, while on an R/W we just extend the index relation by 1 block.\n\nWhat's the exact error ? Are you able to provide a backtrace ?\n\n> To reproduce, you need a query that:\n> \n> 1. Executes parallel BTree index scan;\n> 2. Has an IN-list of size > 1;\n\nDo you mean you have an index on col1 and a query condition like: col1 IN (a,b,c...) ?\n\n> 3. Has an additional index filter that makes it impossible to satisfy the\n> first IN-list condition.\n\n.. AND col1::text||'foo' = '';\nI think you mean that the \"impossible\" condition makes it so that a btree\nworker exits early.\n\n> (We encountered such a query, and therefore the bug, on a production instance.)\n\nCould you send the \"shape\" of the query or its plan, obfuscated and redacted as\nneed be ?\n\n-- \nJustin\n\n\n", "msg_date": "Wed, 9 Sep 2020 23:22:09 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Fix for parallel BTree initialization bug" }, { "msg_contents": "On Tue, Sep 8, 2020 at 11:55 PM Jameson, Hunter 'James'\n<hunjmes@amazon.com> wrote:\n>\n> Hi, I ran across a small (but annoying) bug in initializing parallel BTree scans, which causes the parallel-scan state machine to get confused. The fix is one line; the description is a bit longer—\n>\n>\n>\n> Before, function _bt_first() would exit immediately if the specified scan keys could never be satisfied--without notifying other parallel workers, if any, that the scan key was done.\n>\n\nThe first question that comes to mind is how is it possible that for\none of the workers specified scan keys is not satisfied while for\nothers it is satisfied? I think it is possible when other workers are\nstill working on the previous scan key and this worker has moved to\nthe next scan key. If not, then what is the other case?\n\n> This moved that particular worker to a scan key beyond what was in the shared parallel-query state, so that it would later try to read in \"InvalidBlockNumber\", without recognizing it as a special sentinel value.\n>\n\nNow, if it happens as I mentioned then the other workers should not\ntry to advance their scan because their local scan key will be lesser\nthan shared key. Basically, they should return from the below\ncondition:\n_bt_parallel_seize()\n{\n..\nif (so->arrayKeyCount < btscan->btps_arrayKeyCount)\n{\n/* Parallel scan has already advanced to a new set of scankeys. */\nstatus = false;\n}\n..\n}\n\nAfter this, those workers will also update their scan key and move\nforward from there. So, I am not seeing how this could create a\nproblem.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Thu, 10 Sep 2020 17:28:05 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Fix for parallel BTree initialization bug" }, { "msg_contents": "Against all odds, I was able to reproduce this.\n\nbegin;\nCREATE TABLE t AS SELECT generate_series(1,999999)i;\nALTER TABLE t SET (parallel_workers=2, autovacuum_enabled=off);\nCREATE INDEX ON t(i);\ncommit;\n\nSET parallel_leader_participation=off; SET min_parallel_table_scan_size=0; SET enable_bitmapscan=off; SET enable_indexonlyscan=off; SET enable_seqscan=off;\nexplain(analyze , verbose on) SELECT COUNT(1) FROM t a WHERE a.i>555 AND i IN ( 333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499,500,501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666 ) ORDER BY 1;\n\nWhich gives a plan like:\n Sort (cost=5543.71..5543.72 rows=1 width=8)\n Sort Key: (count(1))\n -> Finalize Aggregate (cost=5543.69..5543.70 rows=1 width=8)\n -> Gather (cost=5543.48..5543.69 rows=2 width=8)\n Workers Planned: 2\n -> Partial Aggregate (cost=4543.48..4543.49 rows=1 width=8)\n -> Parallel Index Scan using t_i_idx on t a (cost=0.42..4204.92 rows=135423 width=0)\n\nI don't get an error, on read-only hot standby. I do get inconsistent results,\nincluding on primary server.\n\ncount | 222\ncount | 214\n\nThis appears to be a bug in commit 569174f1b btree: Support parallel index scans.\n\nI've added your patch here:\nhttps://commitfest.postgresql.org/30/2729/\n\nIn the course of reproducing this, I also added:\n@@ -1972,2 +1975,3 @@ _bt_readnextpage(IndexScanDesc scan, BlockNumber blkno, ScanDirection dir)\n rel = scan->indexRelation;\n+ Assert(BlockNumberIsValid(blkno));\n\n-- \nJustin\n\n\n", "msg_date": "Thu, 10 Sep 2020 21:37:28 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Fix for parallel BTree initialization bug" }, { "msg_contents": "Nice repro, thanks!\r\n--\r\nJames Hunter, Amazon Web Services (AWS)\r\n\r\nOn 9/10/20 7:37 PM, Justin Pryzby wrote:\r\n> Against all odds, I was able to reproduce this.\r\n> \r\n> begin;\r\n> CREATE TABLE t AS SELECT generate_series(1,999999)i;\r\n> ALTER TABLE t SET (parallel_workers=2, autovacuum_enabled=off);\r\n> CREATE INDEX ON t(i);\r\n> commit;\r\n> \r\n> SET parallel_leader_participation=off; SET min_parallel_table_scan_size=0; SET enable_bitmapscan=off; SET enable_indexonlyscan=off; SET enable_seqscan=off;\r\n> explain(analyze , verbose on) SELECT COUNT(1) FROM t a WHERE a.i>555 AND i IN ( 333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499,500,501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666 ) ORDER BY 1;\r\n> \r\n> Which gives a plan like:\r\n> Sort (cost=5543.71..5543.72 rows=1 width=8)\r\n> Sort Key: (count(1))\r\n> -> Finalize Aggregate (cost=5543.69..5543.70 rows=1 width=8)\r\n> -> Gather (cost=5543.48..5543.69 rows=2 width=8)\r\n> Workers Planned: 2\r\n> -> Partial Aggregate (cost=4543.48..4543.49 rows=1 width=8)\r\n> -> Parallel Index Scan using t_i_idx on t a (cost=0.42..4204.92 rows=135423 width=0)\r\n> \r\n> I don't get an error, on read-only hot standby. I do get inconsistent results,\r\n> including on primary server.\r\n> \r\n> count | 222\r\n> count | 214\r\n> \r\n> This appears to be a bug in commit 569174f1b btree: Support parallel index scans.\r\n> \r\n> I've added your patch here:\r\n> https://commitfest.postgresql.org/30/2729/\r\n> \r\n> In the course of reproducing this, I also added:\r\n> @@ -1972,2 +1975,3 @@ _bt_readnextpage(IndexScanDesc scan, BlockNumber blkno, ScanDirection dir)\r\n> rel = scan->indexRelation;\r\n> + Assert(BlockNumberIsValid(blkno));\r\n> \r\n> --\r\n> Justin\r\n> \r\n> \r\n", "msg_date": "Thu, 10 Sep 2020 22:32:13 -0700", "msg_from": "\"Hunter, James\" <hunjmes@amazon.com>", "msg_from_op": false, "msg_subject": "Re: Fix for parallel BTree initialization bug" }, { "msg_contents": "On Fri, Sep 11, 2020 at 8:07 AM Justin Pryzby <pryzby@telsasoft.com> wrote:\n>\n> Against all odds, I was able to reproduce this.\n>\n\nThanks, this helps me to understand the problem. So whats going on\nhere is that once one of the workers has moved to the next set of scan\nkeys without incrementing parallel shared key count the other workers\ncan try to join the on-going scan with a different set of keys which\ncan lead to unpredictable behavior which is seen by both you and\nJames. In your case, it scanned the blocks twice for the same set of\nscan keys due to which you are getting more rows than actual rows to\nbe returned by scan and in the case of James, one of the workers\nchanged it scan block to InvalidBlockNumber (basically start of scan)\nduring the scan which lead to the problem.\n\nSo the fix provided by James is correct. I have slightly adjusted the\ncommit message in the attached. It needs to be backpatched till 10\nwhere this feature was introduced.\n\nI have tested this on HEAD. It would be great if you can verify in\nback branches as well. I'll also do it before commit.\n\n-- \nWith Regards,\nAmit Kapila.", "msg_date": "Fri, 11 Sep 2020 16:41:22 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Fix for parallel BTree initialization bug" }, { "msg_contents": "On Fri, Sep 11, 2020 at 4:41 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Fri, Sep 11, 2020 at 8:07 AM Justin Pryzby <pryzby@telsasoft.com> wrote:\n> >\n> I have tested this on HEAD. It would be great if you can verify in\n> back branches as well. I'll also do it before commit.\n>\n\nI am planning to push this tomorrow after doing testing on\nback-branches. Let me know if you have any comments.\n\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Mon, 14 Sep 2020 18:07:09 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Fix for parallel BTree initialization bug" }, { "msg_contents": "On Mon, Sep 14, 2020 at 5:37 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> I am planning to push this tomorrow after doing testing on\n> back-branches. Let me know if you have any comments.\n\nThe fix seems sensible to me.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Mon, 14 Sep 2020 10:55:56 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: Fix for parallel BTree initialization bug" }, { "msg_contents": "On Mon, Sep 14, 2020 at 11:26 PM Peter Geoghegan <pg@bowt.ie> wrote:\n>\n> On Mon, Sep 14, 2020 at 5:37 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > I am planning to push this tomorrow after doing testing on\n> > back-branches. Let me know if you have any comments.\n>\n> The fix seems sensible to me.\n>\n\nThanks, I think it is better to wait for a day or two as yesterday\nonly we stamped 13 and we need to backpatch this.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 15 Sep 2020 08:28:38 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Fix for parallel BTree initialization bug" }, { "msg_contents": "Amit Kapila <amit.kapila16@gmail.com> writes:\n> On Mon, Sep 14, 2020 at 11:26 PM Peter Geoghegan <pg@bowt.ie> wrote:\n>> The fix seems sensible to me.\n\n> Thanks, I think it is better to wait for a day or two as yesterday\n> only we stamped 13 and we need to backpatch this.\n\nRight, please avoid pushing anything non-critical to REL_13_STABLE\nuntil you see the git tag appear. I doubt we will need to re-wrap\nthe tarballs, but you never know.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 14 Sep 2020 23:24:55 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Fix for parallel BTree initialization bug" }, { "msg_contents": "On Tue, Sep 15, 2020 at 8:54 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Amit Kapila <amit.kapila16@gmail.com> writes:\n> > On Mon, Sep 14, 2020 at 11:26 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> >> The fix seems sensible to me.\n>\n> > Thanks, I think it is better to wait for a day or two as yesterday\n> > only we stamped 13 and we need to backpatch this.\n>\n> Right, please avoid pushing anything non-critical to REL_13_STABLE\n> until you see the git tag appear. I doubt we will need to re-wrap\n> the tarballs, but you never know.\n>\n\nPushed now. Sorry Peter, I forgot to give you reviewer credit in the\ncommit message but I really appreciate your nod for this patch.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Thu, 17 Sep 2020 18:21:59 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Fix for parallel BTree initialization bug" } ]
[ { "msg_contents": "Hi,\n\nJeff Janes in [1] found that I ([2]) broke autovacuum cancellations. It\nobviously would be good to add a test for this, but it seems hard to\nhave that be reliable given how long it can take for autovacuum actually\nget around to vacuum a specific table.\n\nThat made me wonder if it'd be worthwhile to add an option that'd make\nuser invoked VACUUM be interruptible by conflicting lock requests, just\nlike autovacuum is.\n\nThat's actually something I've wanted, and see other people want, a\ncouple times. Sometimes one wants to vacuum a table, but not block out\nmore important things like DDL. Which isn't really possible right now.\n\nSo how about adding an INTERRUPTIBLE option to VACUUM and ANALYZE?\n\nImplementation wise it seems like the best way to implement this would\nbe to replace PROC_VACUUM_FOR_WRAPAROUND with\nPROC_INTERRUPTIBLE_VACANALYZE or such (i.e. inverting the meaning).\n\nOne question I'm a bit split on is whether we'd want to continue\nrestricting the signalling in ProcSleep() to commands running VACUUM or\nANALYZE.\n\nWe could have a generic PROC_INTERRUPTIBLE_COMMAND or such, and have\ndeadlock.c / proc.c trigger whether to kill based on just that, without\nlooking at PROC_IS_AUTOVACUUM / PROC_IN_VACUUM.\n\nAlternatively, if we do want to restrict it to VACUUM and ANALYZE, we'd\nhave to re-introduce PROC_IN_ANALYZE ;). After 12 years of not being\nused and removed just weeks ago...\n\nGreetings,\n\nAndres Freund\n\n[1] https://postgr.es/m/20200827213506.4baaanygq62q7pcj%40alap3.anarazel.de\n[2] https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=d72f6c750\n\n\n", "msg_date": "Tue, 8 Sep 2020 11:49:36 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "VACUUM (INTERRUPTIBLE)?" }, { "msg_contents": "On Tue, Sep 8, 2020 at 8:49 PM Andres Freund <andres@anarazel.de> wrote:\n\n> Hi,\n>\n> Jeff Janes in [1] found that I ([2]) broke autovacuum cancellations. It\n> obviously would be good to add a test for this, but it seems hard to\n> have that be reliable given how long it can take for autovacuum actually\n> get around to vacuum a specific table.\n>\n> That made me wonder if it'd be worthwhile to add an option that'd make\n> user invoked VACUUM be interruptible by conflicting lock requests, just\n> like autovacuum is.\n>\n> That's actually something I've wanted, and see other people want, a\n> couple times. Sometimes one wants to vacuum a table, but not block out\n> more important things like DDL. Which isn't really possible right now.\n>\n> So how about adding an INTERRUPTIBLE option to VACUUM and ANALYZE?\n>\n> Implementation wise it seems like the best way to implement this would\n> be to replace PROC_VACUUM_FOR_WRAPAROUND with\n> PROC_INTERRUPTIBLE_VACANALYZE or such (i.e. inverting the meaning).\n>\n> One question I'm a bit split on is whether we'd want to continue\n> restricting the signalling in ProcSleep() to commands running VACUUM or\n> ANALYZE.\n>\n> We could have a generic PROC_INTERRUPTIBLE_COMMAND or such, and have\n> deadlock.c / proc.c trigger whether to kill based on just that, without\n> looking at PROC_IS_AUTOVACUUM / PROC_IN_VACUUM.\n>\n> Alternatively, if we do want to restrict it to VACUUM and ANALYZE, we'd\n> have to re-introduce PROC_IN_ANALYZE ;). After 12 years of not being\n> used and removed just weeks ago...\n>\n\nOne thing I've been wanting many times but never properly got around to\ninvestigating how much work it would be to make happen, was to be able to\ntrigger an autovacuum manually (yeah, strange choice of terms). That is,\ninstead of the above, you'd have something like \"VACUUM BACKGROUND\" which\nwould trigger an autovacuum worker to do the work, and then release your\nsession. The points then being both (1) the ability to interrupt it, and\n(2) that it'd run in the backgorund and thus the foreground session could\ndisconnect.\n\nI think both would probably solve your problem, and being able to trigger a\nbackground one would add some extra value? But we'd have to figure out and\nbe clear about what to do if all workers are busy for example - queue or\nerror?\n\nWorth considering, or am I missing something?\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 Tue, Sep 8, 2020 at 8:49 PM Andres Freund <andres@anarazel.de> wrote:Hi,\n\nJeff Janes in [1] found that I ([2]) broke autovacuum cancellations. It\nobviously would be good to add a test for this, but it seems hard to\nhave that be reliable given how long it can take for autovacuum actually\nget around to vacuum a specific table.\n\nThat made me wonder if it'd be worthwhile to add an option that'd make\nuser invoked VACUUM be interruptible by conflicting lock requests, just\nlike autovacuum is.\n\nThat's actually something I've wanted, and see other people want, a\ncouple times. Sometimes one wants to vacuum a table, but not block out\nmore important things like DDL. Which isn't really possible right now.\n\nSo how about adding an INTERRUPTIBLE option to VACUUM and ANALYZE?\n\nImplementation wise it seems like the best way to implement this would\nbe to replace PROC_VACUUM_FOR_WRAPAROUND with\nPROC_INTERRUPTIBLE_VACANALYZE or such (i.e. inverting the meaning).\n\nOne question I'm a bit split on is whether we'd want to continue\nrestricting the signalling in ProcSleep() to commands running VACUUM or\nANALYZE.\n\nWe could have a generic PROC_INTERRUPTIBLE_COMMAND or such, and have\ndeadlock.c / proc.c trigger whether to kill based on just that, without\nlooking at PROC_IS_AUTOVACUUM / PROC_IN_VACUUM.\n\nAlternatively, if we do want to restrict it to VACUUM and ANALYZE, we'd\nhave to re-introduce PROC_IN_ANALYZE ;). After 12 years of not being\nused and removed just weeks ago...One thing I've been wanting many times but never properly got around to investigating how much work it would be to make happen, was to be able to trigger an autovacuum manually (yeah, strange choice of terms). That is, instead of the above, you'd have something like \"VACUUM BACKGROUND\" which would trigger an autovacuum worker to do the work, and then release your session. The points then being both (1) the ability to interrupt it, and (2) that it'd run in the backgorund and thus the foreground session could disconnect.I think both would probably solve your problem, and being able to trigger a background one would add some extra value? But we'd have to figure out and be clear about what to do if all workers are busy for example - queue or error?Worth considering, or am I missing something?--  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Tue, 8 Sep 2020 22:30:40 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: VACUUM (INTERRUPTIBLE)?" }, { "msg_contents": "On 2020-Sep-08, Andres Freund wrote:\n\n> That made me wonder if it'd be worthwhile to add an option that'd make\n> user invoked VACUUM be interruptible by conflicting lock requests, just\n> like autovacuum is.\n\nYeah, I recall a request for this in the past, too.\n\n> So how about adding an INTERRUPTIBLE option to VACUUM and ANALYZE?\n\n+1 on adding it to VACUUM. I'm not sure about ANALYZE ... most of the\ntime it is not as bad as VACUUM in terms of blocking other things, and\nthings get ugly if that ANALYZE is part of a transaction. I think I'd\nleave that out, since we don't have to cover all DDL that could take\nShareUpdateExclusive lock (CIC etc). VACUUM is especially problematic,\nISTM, which is we would do it for that.\n\n> Alternatively, if we do want to restrict it to VACUUM and ANALYZE, we'd\n> have to re-introduce PROC_IN_ANALYZE ;). After 12 years of not being\n> used and removed just weeks ago...\n\nHah :-)\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 8 Sep 2020 17:36:00 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: VACUUM (INTERRUPTIBLE)?" }, { "msg_contents": "Hi,\n\nOn 2020-09-08 17:36:00 -0300, Alvaro Herrera wrote:\n> On 2020-Sep-08, Andres Freund wrote:\n> \n> > That made me wonder if it'd be worthwhile to add an option that'd make\n> > user invoked VACUUM be interruptible by conflicting lock requests, just\n> > like autovacuum is.\n> \n> Yeah, I recall a request for this in the past, too.\n> \n> > So how about adding an INTERRUPTIBLE option to VACUUM and ANALYZE?\n> \n> +1 on adding it to VACUUM. I'm not sure about ANALYZE ... most of the\n> time it is not as bad as VACUUM in terms of blocking other things, and\n> things get ugly if that ANALYZE is part of a transaction. I think I'd\n> leave that out, since we don't have to cover all DDL that could take\n> ShareUpdateExclusive lock (CIC etc). VACUUM is especially problematic,\n> ISTM, which is we would do it for that.\n\nANALYZE sometimes is worse than VACUUM in some ways, it'll often take\nlonger on large tables (more random IO, no freeze map equivalent). And\nthere's still TRUNCATE / DROP TABLE etc that you want to be able to\ninterrupt (auto-)analyze.\n\nI'm not sure it's really necessary to distinguish transaction /\nnon-transactional for ANALYZE. We continue to wait for the lock, right?\nSo signalling the transaction is fine, it'll error out. Even in the\ncase of ANALYZE in a subtransaction, we'll not do something incorrect,\nwe might just wait, if the top level transaction also has a lock, and\ndoesn't abort immediately.\n\nSo it doesn't seem that useful to not make manual analyze interruptible?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 8 Sep 2020 14:36:02 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: VACUUM (INTERRUPTIBLE)?" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> So it doesn't seem that useful to not make manual analyze interruptible?\n\nI find the main attraction of this idea is that instead of saying\n\"autovacuum/autoanalyze have these magic behaviors\", we can say\n\"autovacuum/autoanalyze use option FOO\". So whatever behavior\nautoanalyze has today, we should make available to manual analyze,\nwithout quibbling too hard over how much of a use-case there is.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 08 Sep 2020 18:37:05 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: VACUUM (INTERRUPTIBLE)?" }, { "msg_contents": "Hi,\n\nOn 2020-09-08 22:30:40 +0200, Magnus Hagander wrote:\n> One thing I've been wanting many times but never properly got around to\n> investigating how much work it would be to make happen, was to be able to\n> trigger an autovacuum manually (yeah, strange choice of terms). That is,\n> instead of the above, you'd have something like \"VACUUM BACKGROUND\" which\n> would trigger an autovacuum worker to do the work, and then release your\n> session. The points then being both (1) the ability to interrupt it, and\n> (2) that it'd run in the backgorund and thus the foreground session could\n> disconnect.\n> \n> I think both would probably solve your problem, and being able to trigger a\n> background one would add some extra value? But we'd have to figure out and\n> be clear about what to do if all workers are busy for example - queue or\n> error?\n> \n> Worth considering, or am I missing something?\n\nIt seems like it could be useful in general. Not that much for my case\nhowever. It'd be much easier to test whether vacuum was successfully\ncancelled if we can see the cancellation, which we can't in the\nautovacuum case. And there'd likely be some fairly ugly logic around\nneeding to wait until the \"autovacuum request\" is processed etc,\nincluding the case that all workers are currently busy.\n\nSo my INTERRUPTIBLE idea seems to be a better fit for the tests, and\nindependently quite useful. E.g. wanting to know whether VACUUM errored\nout is useful for scripts that want their VACUUMs to be interruptible,\nand that doesn't work well with the \"backgrounding\" idea of yours.\n\nHaving said that, your idea does seem like it could be helpful. The\ndifficulty seems to depend a bit on the exact desired\nsemantics. E.g. would the \"queue\" command block until vacuum started or\nnot? The latter would obviously be much easier...\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 8 Sep 2020 15:58:05 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: VACUUM (INTERRUPTIBLE)?" }, { "msg_contents": "Hi,\n\nOn 2020-09-08 18:37:05 -0400, Tom Lane wrote:\n> Andres Freund <andres@anarazel.de> writes:\n> > So it doesn't seem that useful to not make manual analyze interruptible?\n> \n> I find the main attraction of this idea is that instead of saying\n> \"autovacuum/autoanalyze have these magic behaviors\", we can say\n> \"autovacuum/autoanalyze use option FOO\". So whatever behavior\n> autoanalyze has today, we should make available to manual analyze,\n> without quibbling too hard over how much of a use-case there is.\n\nYea, I think that's a fair point. It's basically more work to\ndistinguish the two anyway.\n\n\nIt was fairly straight forward to implement the basics of\nINTERRUPTIBLE. However it seems like it might not actually address my\nmain concern, i.e. making this reliably testable with isolation\ntester. At least not the way I envisioned it...\n\nMy idea for the test was to have one isolationtester session start a\nseqscan, which would then reliably block a concurrent VACUUM (FREEZE,\nINTERRUPTIBLE). That'd then give a stable point to switch back to the\nfirst session, which would interrupt the VACUUM by doing a LOCK.\n\nBut because there's no known waiting-for pid for a buffer pin wait, we\ncurrently don't detect that we're blocked :(.\n\n\nNow, it'd not be too hard to make pg_isolation_test_session_is_blocked\nalso report being blocked when we're waiting for a buffer pin (ignoring\ninteresting_pids), similar to the safe snapshot test. However I'm\nworried that that could lead to \"false\" reports of blocking? But maybe\nthat's a small enough risk because there's few unconditional cleanup\nlock acquisitions?\n\nHacking such a wait condition test into\npg_isolation_test_session_is_blocked() successfully allows my test to\nwork for VACUUM.\n\nNot yet sure about what a suitable way to test this for analyze would\nbe, unless we'd also accept VacuumDelay as a wait condition :(. I guess\none fairly easy way would be to include an expression index, and have\nthe expression index acquire an unavailable lock. Which'd allow to\nswitch to another session.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 8 Sep 2020 19:30:40 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: VACUUM (INTERRUPTIBLE)?" }, { "msg_contents": "Hi,\n\nOn 2020-09-08 19:30:40 -0700, Andres Freund wrote:\n> It was fairly straight forward to implement the basics of\n> INTERRUPTIBLE. However it seems like it might not actually address my\n> main concern, i.e. making this reliably testable with isolation\n> tester. At least not the way I envisioned it...\n>\n> My idea for the test was to have one isolationtester session start a\n> seqscan, which would then reliably block a concurrent VACUUM (FREEZE,\n> INTERRUPTIBLE). That'd then give a stable point to switch back to the\n> first session, which would interrupt the VACUUM by doing a LOCK.\n>\n> But because there's no known waiting-for pid for a buffer pin wait, we\n> currently don't detect that we're blocked :(.\n>\n>\n> Now, it'd not be too hard to make pg_isolation_test_session_is_blocked\n> also report being blocked when we're waiting for a buffer pin (ignoring\n> interesting_pids), similar to the safe snapshot test. However I'm\n> worried that that could lead to \"false\" reports of blocking? But maybe\n> that's a small enough risk because there's few unconditional cleanup\n> lock acquisitions?\n>\n> Hacking such a wait condition test into\n> pg_isolation_test_session_is_blocked() successfully allows my test to\n> work for VACUUM.\n\nHere's a patch series implementing that:\n\n0001: Adds INTERRUPTIBLE to VACUUM ANALYZE\n There's quite a few XXX's inside. And it needs some none\n isolationtester test.\n0002: Treat BufferPin as a waiting condition in isolationtest.\n That's the aforementioned workaround.\n0003: A test, finally.\n But it only tests VACUUM, not yet ANALYZE. Perhaps also a test for\n not allowing interruptions, somehow?\n\nClearly WIP, but good enough for some comments, I hope?\n\nA few comments:\n- Right now there can only be one such blocking task, because\n PROC_IS_INTERRUPTIBLE is only set by vacuum / analyze, and the lock\n levels are self exclusive. But it's generically named now, so it seems\n just a matter of time until somebody adds that to other commands. I\n think it's ok to not add support for ProcSleep() killing multiple\n other processes?\n- It's a bit annoying that normal user backends just see a generic\n \"ERROR: canceling statement due to user request\". Do we need something\n better?\n- The order in which VACUUM parameters are documented & implemented\n seems fairly random. Perhaps it'd make sense to reorder\n alphabetically?\n\n\n> Not yet sure about what a suitable way to test this for analyze would\n> be, unless we'd also accept VacuumDelay as a wait condition :(. I guess\n> one fairly easy way would be to include an expression index, and have\n> the expression index acquire an unavailable lock. Which'd allow to\n> switch to another session.\n\nBut here I've not yet done anything. That just seems too ugly & fragile.\n\nGreetings,\n\nAndres Freund", "msg_date": "Tue, 8 Sep 2020 21:11:47 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: VACUUM (INTERRUPTIBLE)?" }, { "msg_contents": "On Wed, Sep 9, 2020 at 12:58 AM Andres Freund <andres@anarazel.de> wrote:\n\n> Hi,\n>\n> On 2020-09-08 22:30:40 +0200, Magnus Hagander wrote:\n> > One thing I've been wanting many times but never properly got around to\n> > investigating how much work it would be to make happen, was to be able to\n> > trigger an autovacuum manually (yeah, strange choice of terms). That is,\n> > instead of the above, you'd have something like \"VACUUM BACKGROUND\" which\n> > would trigger an autovacuum worker to do the work, and then release your\n> > session. The points then being both (1) the ability to interrupt it, and\n> > (2) that it'd run in the backgorund and thus the foreground session could\n> > disconnect.\n> >\n> > I think both would probably solve your problem, and being able to\n> trigger a\n> > background one would add some extra value? But we'd have to figure out\n> and\n> > be clear about what to do if all workers are busy for example - queue or\n> > error?\n> >\n> > Worth considering, or am I missing something?\n>\n> It seems like it could be useful in general. Not that much for my case\n> however. It'd be much easier to test whether vacuum was successfully\n> cancelled if we can see the cancellation, which we can't in the\n> autovacuum case. And there'd likely be some fairly ugly logic around\n>\n\nThat does bring up the other thing that I even put together some hacky\npatch for at one point (long since lost or badly-rebased-into-nothingness)\nwhich is to have the stats collector track on a per-relation basis the\nnumber of autovacuum interruptions that have happened on a specific table :)\n\nBut yes, with that it would still not be *as easy* to use, definitely.\n\n\n> needing to wait until the \"autovacuum request\" is processed etc,\n> including the case that all workers are currently busy.\n\n\n> So my INTERRUPTIBLE idea seems to be a better fit for the tests, and\n> independently quite useful. E.g. wanting to know whether VACUUM errored\n> out is useful for scripts that want their VACUUMs to be interruptible,\n> and that doesn't work well with the \"backgrounding\" idea of yours.\n>\n> Having said that, your idea does seem like it could be helpful. The\n> difficulty seems to depend a bit on the exact desired\n> semantics. E.g. would the \"queue\" command block until vacuum started or\n> not? The latter would obviously be much easier...\n\n\nYeah, that's where I stalled in my own thoughts about it I think. OTOH, why\nwait for it to start, if you're not waiting for it to finish... But also,\nif there is a max size of the queue, what do you do if you hit that one?\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, Sep 9, 2020 at 12:58 AM Andres Freund <andres@anarazel.de> wrote:Hi,\n\nOn 2020-09-08 22:30:40 +0200, Magnus Hagander wrote:\n> One thing I've been wanting many times but never properly got around to\n> investigating how much work it would be to make happen, was to be able to\n> trigger an autovacuum manually (yeah, strange choice of terms). That is,\n> instead of the above, you'd have something like \"VACUUM BACKGROUND\" which\n> would trigger an autovacuum worker to do the work, and then release your\n> session. The points then being both (1) the ability to interrupt it, and\n> (2) that it'd run in the backgorund and thus the foreground session could\n> disconnect.\n> \n> I think both would probably solve your problem, and being able to trigger a\n> background one would add some extra value? But we'd have to figure out and\n> be clear about what to do if all workers are busy for example - queue or\n> error?\n> \n> Worth considering, or am I missing something?\n\nIt seems like it could be useful in general. Not that much for my case\nhowever. It'd be much easier to test whether vacuum was successfully\ncancelled if we can see the cancellation, which we can't in the\nautovacuum case. And there'd likely be some fairly ugly logic aroundThat does bring up the other thing that I even put together some hacky patch for at one point (long since lost or badly-rebased-into-nothingness) which is to have the stats collector track on a per-relation basis the number of autovacuum interruptions that have happened on a specific table :)But yes, with that it would still not be *as easy* to use, definitely. \nneeding to wait until the \"autovacuum request\" is processed etc,\nincluding the case that all workers are currently busy. \n\nSo my INTERRUPTIBLE idea seems to be a better fit for the tests, and\nindependently quite useful. E.g. wanting to know whether VACUUM errored\nout is useful for scripts that want their VACUUMs to be interruptible,\nand that doesn't work well with the \"backgrounding\" idea of yours.\n\nHaving said that, your idea does seem like it could be helpful. The\ndifficulty seems to depend a bit on the exact desired\nsemantics. E.g. would the \"queue\" command block until vacuum started or\nnot? The latter would obviously be much easier...Yeah, that's where I stalled in my own thoughts about it I think. OTOH, why wait for it to start, if you're not waiting for it to finish... But also, if there is a max size of the queue, what do you do if you hit that one?--  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Wed, 9 Sep 2020 18:07:31 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: VACUUM (INTERRUPTIBLE)?" }, { "msg_contents": "Hi,\n\nOn 2020-09-08 21:11:47 -0700, Andres Freund wrote:\n> > Not yet sure about what a suitable way to test this for analyze would\n> > be, unless we'd also accept VacuumDelay as a wait condition :(. I guess\n> > one fairly easy way would be to include an expression index, and have\n> > the expression index acquire an unavailable lock. Which'd allow to\n> > switch to another session.\n> \n> But here I've not yet done anything. That just seems too ugly & fragile.\n\nI found a better way after a bunch of tinkering. Having an\nisolationtester session lock pg_class in SHARE mode works, because both\nVACUUM and ANALYZE update the relation's row. I *think* this is\nreliable, due to the report_multiple_error_messages() logic.\n\nThis version also adds setting of PROC_INTERRUPTIBLE for ANALYZE\n(INTERUPTIBLE), which the previous version didn't yet contain. As\ncurrently implemented this means that autovacuum started ANALYZEs are\ninterruptible, which they were not before. That's dead trivial to\nchange, but to me it makes sense to leave it this way. But I also see an\nargument that it'd be better to do so separately?\n\n\n> - It's a bit annoying that normal user backends just see a generic\n> \"ERROR: canceling statement due to user request\". Do we need something\n> better?\n\nI think this is ok for this iteration, and instead at some point solve\nthis in a bit more generic manner. This isn't the only place where\ncarrying a bit more information about why and by whom a query is\ncancelled would be very useful.\n\nThere's one XXX left in here, which is:\n\n@@ -1340,8 +1338,12 @@ ProcSleep(LOCALLOCK *locallock, LockMethod lockMethodTable)\n LWLockRelease(ProcArrayLock);\n \n /* send the autovacuum worker Back to Old Kent Road */\n+ /*\n+ * FIXME: do we want to continue to identify autovacuum here?\n+ * Could do so based on PROC_IS_AUTOVACUUM.\n+ */\n ereport(DEBUG1,\n- (errmsg(\"sending cancel to blocking autovacuum PID %d\",\n+ (errmsg(\"sending cancel to blocking autovacuum|XXX PID %d\",\n pid),\n errdetail_log(\"%s\", logbuf.data)));\n \n\ngiven that this is a DEBUG1 I'm inclined to just replace this with\n\"... blocking interruptible process with PID %d\"\nor such?\n\nComments?\n\nGreetings,\n\nAndres Freund", "msg_date": "Wed, 30 Sep 2020 20:27:02 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: VACUUM (INTERRUPTIBLE)?" } ]
[ { "msg_contents": "This is to pull together a couple of recent threads that are seemingly\nunrelated to $SUBJECT.\n\nOver in the long thread at [1] we've agreed to try to make the backend\ncode actually do what assorted comments claim it does, namely allow\nSIGQUIT to be accepted at any point after a given process has established\nits signal handlers. (Right now, it mostly is not accepted during error\nrecovery, but there's no clear reason to preserve that exception.)\n\nOf course, this is only safe if the SIGQUIT handler is safe to be invoked\nanywhere, so I did a quick survey of backend signal handlers to see if\nthat is true. I immediately found pgarch_exit() which surely is not. It\nturns out that Horiguchi-san already noticed that and proposed to fix it,\nwithin the seemingly entirely unrelated patch series for a shared-memory\nbased stats collector (see patch 0001 in [2]). I think we should go ahead\nand commit that, and maybe even back-patch it. There seems no good reason\nfor the archiver to treat SIGQUIT as nonfatal when other postmaster\nchildren do not.\n\nAnother thing I found is startup_die() in postmaster.c, which catches\nSIGQUIT during the authentication phase of a new backend. This calls\nproc_exit(1), which (a) is unsafe on its face, and (b) potentially\ndemotes a SIGQUIT into something that will not cause the parent postmaster\nto perform a DB-wide restart. There seems no good reason for that\nbehavior, either. I propose that we use SignalHandlerForCrashExit\nfor SIGQUIT here too.\n\nIn passing, it's worth noting that startup_die() isn't really much safer\nfor SIGTERM than it is for SIGQUIT; the only argument for distinguishing\nthose is that code that applies BlockSig will at least manage to block the\nformer. So it's slightly tempting to drop startup_die() altogether in\nfavor of using SignalHandlerForCrashExit for the SIGTERM-during-auth case\ntoo. However, that'd have the effect of causing a \"fast shutdown\" to get\nconverted to a panic if it happens while any sessions are in\nauthentication phase, so I think this cure is likely worse than the\ndisease.\n\nWorth reading in connection with this is the thread that led up to\ncommits 8e19a8264 et al [3]. We had a long discussion about how\nquickdie() and startup_die() might be made safe(r), without any\nreal consensus emerging about any alternatives being better than the\nstatus quo. I still don't have an improvement idea for quickdie();\nI don't want to give up trying to send a message to the client.\nNote, however, that quickdie() does end with _exit(2) so that at\nleast it's not trying to execute arbitrary process-cleanup code.\n\nIn short then, I want to ensure that postmaster children's SIGQUIT\nhandlers always end with _exit(2) rather than some other exit method.\nWe have two exceptions now and they need to get fixed.\n\n\t\t\tregards, tom lane\n\n[1] https://www.postgresql.org/message-id/flat/CALDaNm1d1hHPZUg3xU4XjtWBOLCrA%2B-2cJcLpw-cePZ%3DGgDVfA%40mail.gmail.com\n[2] https://www.postgresql.org/message-id/20200908.175557.617150409868541587.horikyota.ntt%40gmail.com\n[3] https://www.postgresql.org/message-id/flat/CAOMx_OAuRUHiAuCg2YgicZLzPVv5d9_H4KrL_OFsFP%3DVPekigA%40mail.gmail.com\n\n\n", "msg_date": "Tue, 08 Sep 2020 17:39:24 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "SIGQUIT handling, redux" }, { "msg_contents": "Greetings,\n\n* Tom Lane (tgl@sss.pgh.pa.us) wrote:\n> This is to pull together a couple of recent threads that are seemingly\n> unrelated to $SUBJECT.\n> \n> Over in the long thread at [1] we've agreed to try to make the backend\n> code actually do what assorted comments claim it does, namely allow\n> SIGQUIT to be accepted at any point after a given process has established\n> its signal handlers. (Right now, it mostly is not accepted during error\n> recovery, but there's no clear reason to preserve that exception.)\n> \n> Of course, this is only safe if the SIGQUIT handler is safe to be invoked\n> anywhere, so I did a quick survey of backend signal handlers to see if\n> that is true. I immediately found pgarch_exit() which surely is not. It\n> turns out that Horiguchi-san already noticed that and proposed to fix it,\n> within the seemingly entirely unrelated patch series for a shared-memory\n> based stats collector (see patch 0001 in [2]). I think we should go ahead\n> and commit that, and maybe even back-patch it. There seems no good reason\n> for the archiver to treat SIGQUIT as nonfatal when other postmaster\n> children do not.\n\nAs I mentioned over there, I agree that we should do this and we should\nfurther have the statistics collector also do so, which currently sets\nup SIGQUIT with ShutdownRequestPending() and in its loop decides it's\nfine to write out the stats file (which we're going to remove during\nrecovery anyway...) and then call exit(0). I also think we should\nback-patch these changes, as the commit mentioned in Horiguchi-san's\npatch for pgarch_exit() was.\n\n> Another thing I found is startup_die() in postmaster.c, which catches\n> SIGQUIT during the authentication phase of a new backend. This calls\n> proc_exit(1), which (a) is unsafe on its face, and (b) potentially\n> demotes a SIGQUIT into something that will not cause the parent postmaster\n> to perform a DB-wide restart. There seems no good reason for that\n> behavior, either. I propose that we use SignalHandlerForCrashExit\n> for SIGQUIT here too.\n\nYikes, agreed.\n\n> In passing, it's worth noting that startup_die() isn't really much safer\n> for SIGTERM than it is for SIGQUIT; the only argument for distinguishing\n> those is that code that applies BlockSig will at least manage to block the\n> former. So it's slightly tempting to drop startup_die() altogether in\n> favor of using SignalHandlerForCrashExit for the SIGTERM-during-auth case\n> too. However, that'd have the effect of causing a \"fast shutdown\" to get\n> converted to a panic if it happens while any sessions are in\n> authentication phase, so I think this cure is likely worse than the\n> disease.\n\nAgreed, that's definitely no good.\n\n> Worth reading in connection with this is the thread that led up to\n> commits 8e19a8264 et al [3]. We had a long discussion about how\n> quickdie() and startup_die() might be made safe(r), without any\n> real consensus emerging about any alternatives being better than the\n> status quo. I still don't have an improvement idea for quickdie();\n> I don't want to give up trying to send a message to the client.\n> Note, however, that quickdie() does end with _exit(2) so that at\n> least it's not trying to execute arbitrary process-cleanup code.\n> \n> In short then, I want to ensure that postmaster children's SIGQUIT\n> handlers always end with _exit(2) rather than some other exit method.\n> We have two exceptions now and they need to get fixed.\n\nI agree we should fix these.\n\nThanks,\n\nStephen", "msg_date": "Wed, 9 Sep 2020 10:39:00 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "Stephen Frost <sfrost@snowman.net> writes:\n> * Tom Lane (tgl@sss.pgh.pa.us) wrote:\n>> Of course, this is only safe if the SIGQUIT handler is safe to be invoked\n>> anywhere, so I did a quick survey of backend signal handlers to see if\n>> that is true. I immediately found pgarch_exit() which surely is not. It\n>> turns out that Horiguchi-san already noticed that and proposed to fix it,\n>> within the seemingly entirely unrelated patch series for a shared-memory\n>> based stats collector (see patch 0001 in [2]). I think we should go ahead\n>> and commit that, and maybe even back-patch it. There seems no good reason\n>> for the archiver to treat SIGQUIT as nonfatal when other postmaster\n>> children do not.\n\n> As I mentioned over there, I agree that we should do this and we should\n> further have the statistics collector also do so, which currently sets\n> up SIGQUIT with ShutdownRequestPending() and in its loop decides it's\n> fine to write out the stats file (which we're going to remove during\n> recovery anyway...) and then call exit(0).\n\nI noticed that that was different from everything else, but it's not\nactually signal-unsafe, so it seems like a different topic from what\nI'm on about at the moment. I don't mind if you or somebody else\nwants to change it, but I don't see it as a back-patchable bug fix.\n\n> I also think we should\n> back-patch these changes, as the commit mentioned in Horiguchi-san's\n> patch for pgarch_exit() was.\n\nAgreed; I'll go make it happen.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 09 Sep 2020 10:46:28 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "I wrote:\n> Stephen Frost <sfrost@snowman.net> writes:\n>> As I mentioned over there, I agree that we should do this and we should\n>> further have the statistics collector also do so, which currently sets\n>> up SIGQUIT with ShutdownRequestPending() and in its loop decides it's\n>> fine to write out the stats file (which we're going to remove during\n>> recovery anyway...) and then call exit(0).\n\n> I noticed that that was different from everything else, but it's not\n> actually signal-unsafe, so it seems like a different topic from what\n> I'm on about at the moment. I don't mind if you or somebody else\n> wants to change it, but I don't see it as a back-patchable bug fix.\n\nNote also that the postmaster actually uses SIGQUIT to command normal\nshutdown of the stats collector (cf reaper(), around line 3125 in HEAD).\nSo this needs a change in signaling conventions, not just internal\ntweaks in the collector. Not a big deal, but it reinforces my feeling\nthat it should be a HEAD-only change.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 09 Sep 2020 10:55:23 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "Hi,\n\nOn 2020-09-08 17:39:24 -0400, Tom Lane wrote:\n> Of course, this is only safe if the SIGQUIT handler is safe to be invoked\n> anywhere, so I did a quick survey of backend signal handlers to see if\n> that is true. I immediately found pgarch_exit() which surely is not. It\n> turns out that Horiguchi-san already noticed that and proposed to fix it,\n> within the seemingly entirely unrelated patch series for a shared-memory\n> based stats collector (see patch 0001 in [2]). I think we should go ahead\n> and commit that, and maybe even back-patch it. There seems no good reason\n> for the archiver to treat SIGQUIT as nonfatal when other postmaster\n> children do not.\n\n+1\n\n\n> Another thing I found is startup_die() in postmaster.c, which catches\n> SIGQUIT during the authentication phase of a new backend. This calls\n> proc_exit(1), which (a) is unsafe on its face, and (b) potentially\n> demotes a SIGQUIT into something that will not cause the parent postmaster\n> to perform a DB-wide restart. There seems no good reason for that\n> behavior, either. I propose that we use SignalHandlerForCrashExit\n> for SIGQUIT here too.\n\nYikes, yea, that seems like an important change.\n\n\nI wish startup_die() weren't named startup_ - every single time I see\nthe name I think it's about the startup process...\n\n\nI think StartupPacketTimeoutHandler is another case?\n\n\n\n> In passing, it's worth noting that startup_die() isn't really much safer\n> for SIGTERM than it is for SIGQUIT; the only argument for distinguishing\n> those is that code that applies BlockSig will at least manage to block the\n> former.\n\nWhich is pretty unconvincing...\n\nI wonder if we could at least *try* to rely on CFR() for a while. It'd\nnot be pretty, but probably doable, to set up a timer inside the signal\nhandler and try to exit using normal mechanisms for a while (some\noverlap with authentication timeout).\n\nThat'd leave the question of what we do once that timer expires. There's\nquite a few possible ways that could reproducibly happen, e.g. if DNS\nlookups are required during auth.\n\nThe long term correct way to handle this would obviously be to\nrestructure everything that happens covered by startup_die() in a\nnon-blocking manner and just rely on CFR(). But that's a tall order to\nget done anytime soon, particularly things like DNS are IIRC pretty hard\nwithout relying on custom libraries.\n\nShorter term I don't really see an alternative to escalating to SIGQUIT\nwhich is obviously terrible.\n\n\n> So it's slightly tempting to drop startup_die() altogether in favor of\n> using SignalHandlerForCrashExit for the SIGTERM-during-auth case too.\n> However, that'd have the effect of causing a \"fast shutdown\" to get\n> converted to a panic if it happens while any sessions are in\n> authentication phase, so I think this cure is likely worse than the\n> disease.\n\nIndeed.\n\n\n> I don't want to give up trying to send a message to the client.\n\nThat still doesn't make much sense to me. The potential for hanging\n(e.g. inside malloc) is so much worse than not sending a message... And\nwe already infer things about the server dying in libpq when the\nconnection just closes (which I am admittedly also not happy about). But\nI also think we can reduce the risk a bit, see below.\n\nI only had one coffee so far (and it looks like the sun has died\noutside), so maybe I'm just slow: But, uh, we don't currently send a\nmessage startup_die(), right?\n\nSo that part is about quickdie()?\n\n\n> Worth reading in connection with this is the thread that led up to\n> commits 8e19a8264 et al [3]. We had a long discussion about how\n> quickdie() and startup_die() might be made safe(r), without any\n> real consensus emerging about any alternatives being better than the\n> status quo. I still don't have an improvement idea for quickdie();\n\nI still think that we should at least mitigate the risk to hang inside\nquickdie() by at least disabling translations (since the rest happens\ninside the pre-allocated error memory context, which should lower the\nrisk). And perhaps do similarly for the memory required for encryption,\nif enabled, and where possible.\n\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 9 Sep 2020 12:26:20 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> I wish startup_die() weren't named startup_ - every single time I see\n> the name I think it's about the startup process...\n\nWe could call it startup_packet_die or something?\n\n> I think StartupPacketTimeoutHandler is another case?\n\nYeah. Although it's a lot less risky, since if the timeout is reached\nwe're almost certainly waiting for client input.\n\n>> In passing, it's worth noting that startup_die() isn't really much safer\n>> for SIGTERM than it is for SIGQUIT; the only argument for distinguishing\n>> those is that code that applies BlockSig will at least manage to block the\n>> former.\n\n> Which is pretty unconvincing...\n\nAgreed, it'd be nice if this were less shaky. On the other hand,\nwe've seen darn few complaints traceable to this AFAIR. I'm not\nreally sure it's worth putting a lot of effort into.\n\n> The long term correct way to handle this would obviously be to\n> restructure everything that happens covered by startup_die() in a\n> non-blocking manner and just rely on CFR(). But that's a tall order to\n> get done anytime soon, particularly things like DNS are IIRC pretty hard\n> without relying on custom libraries.\n\nNot only DNS, but all the various auth libraries would have to be\ncontended with. Lots of work there compared to the likely rewards.\n\n>> I don't want to give up trying to send a message to the client.\n\n> That still doesn't make much sense to me. The potential for hanging\n> (e.g. inside malloc) is so much worse than not sending a message...\n\nWe see backends going through this code on a very regular basis in the\nbuildfarm, but complete hangs are rare as can be. I think you\noverestimate the severity of the problem.\n\n> I only had one coffee so far (and it looks like the sun has died\n> outside), so maybe I'm just slow: But, uh, we don't currently send a\n> message startup_die(), right?\n> So that part is about quickdie()?\n\nRight. Note that startup_die() is pre-authentication, so I'm doubtful\nthat we should tell the would-be client anything about the state of\nthe server at that point, even ignoring these risk factors. (I'm a\nbit inclined to remove the comment suggesting that'd be desirable.)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 09 Sep 2020 16:09:00 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "Hi,\n\nOn 2020-09-09 16:09:00 -0400, Tom Lane wrote:\n> Andres Freund <andres@anarazel.de> writes:\n> > I wish startup_die() weren't named startup_ - every single time I see\n> > the name I think it's about the startup process...\n> \n> We could call it startup_packet_die or something?\n\nYea, I think that'd be good.\n\n\n> > I think StartupPacketTimeoutHandler is another case?\n> \n> Yeah. Although it's a lot less risky, since if the timeout is reached\n> we're almost certainly waiting for client input.\n\nAn adversary could control that to a significant degree - but ordinarily\nI agree...\n\n\n> >> In passing, it's worth noting that startup_die() isn't really much safer\n> >> for SIGTERM than it is for SIGQUIT; the only argument for distinguishing\n> >> those is that code that applies BlockSig will at least manage to block the\n> >> former.\n> \n> > Which is pretty unconvincing...\n> \n> Agreed, it'd be nice if this were less shaky. On the other hand,\n> we've seen darn few complaints traceable to this AFAIR. I'm not\n> really sure it's worth putting a lot of effort into.\n\nNot sure how many would plausibly reach us though. A common reaction\nwill likely just to be to force-restart the server, not to fully\ninvestigate the issue. Particularly because it'll often be once\nsomething already has gone wrong...\n\n\n\n> >> I don't want to give up trying to send a message to the client.\n> \n> > That still doesn't make much sense to me. The potential for hanging\n> > (e.g. inside malloc) is so much worse than not sending a message...\n> \n> We see backends going through this code on a very regular basis in the\n> buildfarm, but complete hangs are rare as can be. I think you\n> overestimate the severity of the problem.\n\nI don't think the BF exercises the problmetic paths to a significant\ndegree. It's mostly local socket connections, and where not it's\nlocalhost. There's no slow DNS, no more complicated authentication\nmethods, no packet loss. How often do we ever actually end up even\ngetting close to any of the paths but immediate shutdowns? And in the\nSIGQUIT path, how often do we end up in the SIGKILL path, masking\npotential deadlocks?\n\n\n> > I only had one coffee so far (and it looks like the sun has died\n> > outside), so maybe I'm just slow: But, uh, we don't currently send a\n> > message startup_die(), right?\n> > So that part is about quickdie()?\n> \n> Right. Note that startup_die() is pre-authentication, so I'm doubtful\n> that we should tell the would-be client anything about the state of\n> the server at that point, even ignoring these risk factors. (I'm a\n> bit inclined to remove the comment suggesting that'd be desirable.)\n\nYea, I think just putting in an editorialized version of your paragraph\nwould make sense.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 9 Sep 2020 13:22:01 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On 2020-09-09 16:09:00 -0400, Tom Lane wrote:\n>> We could call it startup_packet_die or something?\n\n> Yea, I think that'd be good.\n\nI'll make it so.\n\n>> We see backends going through this code on a very regular basis in the\n>> buildfarm, but complete hangs are rare as can be. I think you\n>> overestimate the severity of the problem.\n\n> I don't think the BF exercises the problmetic paths to a significant\n> degree. It's mostly local socket connections, and where not it's\n> localhost. There's no slow DNS, no more complicated authentication\n> methods, no packet loss. How often do we ever actually end up even\n> getting close to any of the paths but immediate shutdowns?\n\nSince we're talking about quickdie(), immediate shutdown/crash restart\nis exactly the case of concern, and the buildfarm exercises it all the\ntime.\n\n> And in the\n> SIGQUIT path, how often do we end up in the SIGKILL path, masking\n> potential deadlocks?\n\nTrue, we can't really tell that. I wonder if we should make the\npostmaster emit a log message when it times out and goes to SIGKILL.\nAfter a few months we could scrape the buildfarm logs and get a\npretty good handle on it.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 09 Sep 2020 16:30:37 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "I wrote:\n> Not only DNS, but all the various auth libraries would have to be\n> contended with. Lots of work there compared to the likely rewards.\n\nWait a minute. The entire authentication cycle happens inside\nInitPostgres, using the backend's normal signal handlers. So\nmaybe we are overthinking the problem. What if we simply postpone\nProcessStartupPacket into that same place, and run it under the same\nrules as we do for authentication? We would waste more cycles than\nwe do now for the case where the client closes the connection without\nsending a startup packet, but not enormously so, I think --- and\noptimizing that case doesn't seem like a high-priority goal anyway.\nAnd cases like DNS lookup taking forever don't seem like any more of\nan issue than auth lookup taking forever.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 09 Sep 2020 16:50:26 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "Hi,\n\nOn 2020-09-09 16:30:37 -0400, Tom Lane wrote:\n> Andres Freund <andres@anarazel.de> writes:\n> > On 2020-09-09 16:09:00 -0400, Tom Lane wrote:\n> >> We could call it startup_packet_die or something?\n> \n> > Yea, I think that'd be good.\n> \n> I'll make it so.\n\nThanks!\n\n\n> >> We see backends going through this code on a very regular basis in the\n> >> buildfarm, but complete hangs are rare as can be. I think you\n> >> overestimate the severity of the problem.\n> \n> > I don't think the BF exercises the problmetic paths to a significant\n> > degree. It's mostly local socket connections, and where not it's\n> > localhost. There's no slow DNS, no more complicated authentication\n> > methods, no packet loss. How often do we ever actually end up even\n> > getting close to any of the paths but immediate shutdowns?\n> \n> Since we're talking about quickdie(), immediate shutdown/crash restart\n> is exactly the case of concern, and the buildfarm exercises it all the\n> time.\n\nYea, but only in simple cases. Largely no SSL / kerberos. Largely\nuntranslated. Mostly the immediate shutdowns aren't when inside plpython\nor such.\n\n\n> > And in the\n> > SIGQUIT path, how often do we end up in the SIGKILL path, masking\n> > potential deadlocks?\n> \n> True, we can't really tell that. I wonder if we should make the\n> postmaster emit a log message when it times out and goes to SIGKILL.\n> After a few months we could scrape the buildfarm logs and get a\n> pretty good handle on it.\n\nI think that'd be a good idea.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 9 Sep 2020 14:06:54 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "I wrote:\n>> Not only DNS, but all the various auth libraries would have to be\n>> contended with. Lots of work there compared to the likely rewards.\n\n> Wait a minute. The entire authentication cycle happens inside\n> InitPostgres, using the backend's normal signal handlers. So\n> maybe we are overthinking the problem. What if we simply postpone\n> ProcessStartupPacket into that same place, and run it under the same\n> rules as we do for authentication?\n\nOr, continuing to look for other answers ...\n\nDuring BackendInitialize we have not yet touched shared memory.\nThis is not incidental but must be so, per its header comment.\nTherefore it seems like we could have these signal handlers (for\nSIGTERM or timeout) do _exit(1), thereby resolving the signal\nunsafety while not provoking a database restart. We don't\ncare whether inside-the-process state is sane, and we shouldn't\nhave changed anything yet in shared memory.\n\nThis is obviously not 100.00% safe, since maybe something could\nviolate these assumptions, but it seems a lot safer than using\nproc_exit() from a signal handler.\n\nOne way to help catch any such assumption-violations is to add\nan assertion that no on_shmem_exit handlers have been set up yet.\nIf there are none, there should be no expectation of having to\nclean up shared state.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 09 Sep 2020 18:00:41 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "Here's a draft patch that I think would be reasonable to back-patch.\n(Before v13, we'd need a bespoke SIGQUIT handler to substitute for\nSignalHandlerForCrashExit, but that's easy enough.)\n\nAside from comment updates, this\n\n* uses SignalHandlerForCrashExit for SIGQUIT\n\n* renames startup_die per your request\n\n* moves BackendInitialize's interrupt-re-disabling code up a bit to\nreduce the scope where these interrupts are active. This doesn't\nmake things a whole lot safer, but it can't hurt.\n\nI'll take a closer look at the idea of using _exit(1) tomorrow,\nbut I'd be pretty hesitant to back-patch that.\n\n\t\t\tregards, tom lane", "msg_date": "Wed, 09 Sep 2020 19:24:55 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "I wrote:\n> Of course, this is only safe if the SIGQUIT handler is safe to be invoked\n> anywhere, so I did a quick survey of backend signal handlers to see if\n> that is true.\n\nThis is straying a bit from the stated topic of this thread, but ...\nI did some further looking around to see whether there were any\nunsafe signal handlers besides SIGQUIT ones. The situation is not\ntoo awful, but I did find several issues not already mentioned\nin this thread:\n\nStartupProcShutdownHandler (SIGTERM)\n\nThis conditionally calls proc_exit(1). The conditions boil down\nto are-we-interrupting-a-system(3)-call, so who knows how safe\nthat is? I wouldn't care to bet that system() doesn't use malloc,\nfor instance. Still, the odds are very good that if a signal did\narrive, it'd be interrupting system()'s waitpid() or equivalent\nkernel call, which is likely safe enough.\n\nbgworker_die (SIGTERM)\n\nCalls ereport(FATAL). This is surely not any safer than, say,\nquickdie(). No, it's worse, because at least that won't try\nto go out via proc_exit().\n\nFloatExceptionHandler (SIGFPE)\n\nCalls ereport(ERROR). This might be okay, though, since the\ntrap should be synchronous with the offending calculation.\nBesides, if you're risking divide by zero or the like in\ncritical code, You're Doing It Wrong.\n\nRecoveryConflictInterrupt (called from SIGUSR1)\n\nCalls a whole boatload of state tests that were never designed\nto be interrupt-safe, such as transaction-state-related inquiries\nin xact.c. The lack of any explicit awareness in this code that\nit's in a signal handler doesn't discourage people from inserting\neven more dubious stuff. I think this needs to be burned to the\nground and rewritten.\n\nStandbyDeadLockHandler (from SIGALRM)\nStandbyTimeoutHandler (ditto)\n\nCalls CancelDBBackends, which just for starters tries to acquire\nan LWLock. I think the only reason we've gotten away with this\nfor this long is the high probability that by the time either\ntimeout fires, we're going to be blocked on a semaphore.\n\nI don't have any ideas about how to fix any of these things,\nbut I thought getting the problems on the record would be good.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 09 Sep 2020 22:07:06 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "From: Tom Lane <tgl@sss.pgh.pa.us>\n> This is straying a bit from the stated topic of this thread, but ...\n> I did some further looking around to see whether there were any\n> unsafe signal handlers besides SIGQUIT ones. The situation is not\n> too awful, but I did find several issues not already mentioned\n> in this thread:\n\nWow, your eyes catch this many issues. (I was just wondering about one or two of them.)\n\nI'm not sure if this is related, but I had been wondering if the following can be what it is now.\n\n\n(1)\nWhen logical replication is used, pg_ctl stop with the default fast mode emits the message about termination of logical replication launcher. Although it's not FATAL or ERROR, but I was a bit startled when I saw this message for the first time. Why should this message be emitted while nothing about other postmaster children are reported? The logical rep launcher ignores SIGINT (SIG_IGN).\n\nLOG: received fast shutdown request\nLOG: aborting any active transactions\nLOG: background worker \"logical replication launcher\" (PID 10056) exited with exit code 1\nLOG: shutting down\nLOG: database system is shut down\n\n\n(2)\nWhen the physical standby stops, a FATAL message is output. It may be annoying to the DBA that monitors messages with high severity.\n\nLOG: received fast shutdown request\nLOG: aborting any active transactions\nFATAL: terminating walreceiver process due to administrator command\nLOG: shutting down\nLOG: database system is shut down\n\n\n(3)\nWhen WaitLatch(EXIT_ON_POSTMASTER_DEATH) detects postmaster death, it calls proc_exit(1). Can we call _exit(1) here likewise?\n\n\nRegards\nTakayuki Tsunakawa\n\n\n\n\n", "msg_date": "Thu, 10 Sep 2020 02:56:37 +0000", "msg_from": "\"tsunakawa.takay@fujitsu.com\" <tsunakawa.takay@fujitsu.com>", "msg_from_op": false, "msg_subject": "RE: SIGQUIT handling, redux" }, { "msg_contents": "At Wed, 09 Sep 2020 10:46:28 -0400, Tom Lane <tgl@sss.pgh.pa.us> wrote in \n> > I also think we should\n> > back-patch these changes, as the commit mentioned in Horiguchi-san's\n> > patch for pgarch_exit() was.\n> \n> Agreed; I'll go make it happen.\n\nThank you for committing this!\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Thu, 10 Sep 2020 19:02:06 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "On Wed, Sep 9, 2020 at 10:07 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> bgworker_die (SIGTERM)\n>\n> Calls ereport(FATAL). This is surely not any safer than, say,\n> quickdie(). No, it's worse, because at least that won't try\n> to go out via proc_exit().\n\nI think bgworker_die() is pretty much a terrible idea. Every\nbackground worker I've written has actually needed to use\nCHECK_FOR_INTERRUPTS(). I think that the only way this could actually\nbe safe is if you have a background worker that never uses ereport()\nitself, so that the ereport() in the signal handler can't be\ninterrupting one that's already happening. This seems unlikely to be\nthe normal case, or anything close to it. Most background workers\nprobably are shared-memory connected and use a lot of PostgreSQL\ninfrastructure and thus ereport() all over the place.\n\nNow what to do about it I don't know exactly, but it would be nice to\ndo something.\n\n> StandbyDeadLockHandler (from SIGALRM)\n> StandbyTimeoutHandler (ditto)\n>\n> Calls CancelDBBackends, which just for starters tries to acquire\n> an LWLock. I think the only reason we've gotten away with this\n> for this long is the high probability that by the time either\n> timeout fires, we're going to be blocked on a semaphore.\n\nYeah, I'm not sure these are so bad. In fact, in the deadlock case, I\nbelieve the old coding was designed to make sure we *had to* be\nblocked on a semaphore, but I'm not sure whether that's still true.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 10 Sep 2020 10:36:23 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> On Wed, Sep 9, 2020 at 10:07 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> bgworker_die (SIGTERM)\n>> Calls ereport(FATAL). This is surely not any safer than, say,\n>> quickdie(). No, it's worse, because at least that won't try\n>> to go out via proc_exit().\n\n> I think bgworker_die() is pretty much a terrible idea.\n\nYeah. It'd likely be better to insist that bgworkers handle SIGTERM\nthe same way backends do, via CHECK_FOR_INTERRUPTS. Not sure how big\na change that would be.\n\n> I think that the only way this could actually\n> be safe is if you have a background worker that never uses ereport()\n> itself, so that the ereport() in the signal handler can't be\n> interrupting one that's already happening.\n\nThat doesn't begin to make it safe, because quite aside from anything\nthat happens in elog.c, we're then going to go out via proc_exit()\nwhich will invoke who knows what.\n\n>> StandbyDeadLockHandler (from SIGALRM)\n>> StandbyTimeoutHandler (ditto)\n>> Calls CancelDBBackends, which just for starters tries to acquire\n>> an LWLock. I think the only reason we've gotten away with this\n>> for this long is the high probability that by the time either\n>> timeout fires, we're going to be blocked on a semaphore.\n\n> Yeah, I'm not sure these are so bad. In fact, in the deadlock case, I\n> believe the old coding was designed to make sure we *had to* be\n> blocked on a semaphore, but I'm not sure whether that's still true.\n\nLooking at this closer, the only code that could get interrupted\nby these timeouts is a call to ProcWaitForSignal, which is\n\nvoid\nProcWaitForSignal(uint32 wait_event_info)\n{\n (void) WaitLatch(MyLatch, WL_LATCH_SET | WL_EXIT_ON_PM_DEATH, 0,\n wait_event_info);\n ResetLatch(MyLatch);\n CHECK_FOR_INTERRUPTS();\n}\n\nInterrupting the latch operations might be safe enough,\nalthough now I'm casting a side-eye at Munro's recent\nchanges to share WaitEvent state all over the place.\nI wonder whether blocking on an LWLock inside the\nsignal handler will break an interrupted WaitLatch.\n\nAlso, man that CHECK_FOR_INTERRUPTS() looks like trouble.\nCould we take that out?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 10 Sep 2020 12:56:55 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "On Thu, Sep 10, 2020 at 12:56 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Also, man that CHECK_FOR_INTERRUPTS() looks like trouble.\n> Could we take that out?\n\nMaybe I'm missing something, but why wouldn't that be a horrible idea?\nWe do not want to have long waits where we refuse to respond to\ninterrupts.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 10 Sep 2020 14:26:59 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> On Thu, Sep 10, 2020 at 12:56 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> Also, man that CHECK_FOR_INTERRUPTS() looks like trouble.\n>> Could we take that out?\n\n> Maybe I'm missing something, but why wouldn't that be a horrible idea?\n> We do not want to have long waits where we refuse to respond to\n> interrupts.\n\nIt might be appropriate for some of the callers to do it. But I don't\nsee any great argument why ProcWaitForSignal itself has to do it.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 10 Sep 2020 16:29:23 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "I wrote:\n> I'll take a closer look at the idea of using _exit(1) tomorrow,\n> but I'd be pretty hesitant to back-patch that.\n\nHere's a patch for that; it passes light testing, including forcing\nthe backend through the SIGTERM and timeout code paths. There's\nnot much to it except for changing the signal handlers, but I did\nadd a cross-check that no on-exit handlers have been registered\nbefore we get done with using these signal handlers.\n\nI looked briefly at the idea of postponing ProcessStartupPacket\nuntil InitPostgres has set up a fairly normal environment. It\nseems like it'd take a fair amount of refactoring. I really\ndoubt it's worth the effort, even though the result would be\narguably cleaner logic than what we have now.\n\n\t\t\tregards, tom lane", "msg_date": "Thu, 10 Sep 2020 22:40:06 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "I wrote:\n> I looked briefly at the idea of postponing ProcessStartupPacket\n> until InitPostgres has set up a fairly normal environment. It\n> seems like it'd take a fair amount of refactoring. I really\n> doubt it's worth the effort, even though the result would be\n> arguably cleaner logic than what we have now.\n\nI felt more ambitious this morning and decided to take a harder look\nat this idea. But I soon realized that there would be a concrete\ndisadvantage to delaying ProcessStartupPacket: until we have done that,\nwe don't have the correct value for FrontendProtocol so there is a\nproblem with reporting startup-time failures to the client. At least\nsome such failures, such as \"too many clients already\", are pretty\nroutine so we don't want to downgrade their user-friendliness.\n\nIf memory serves, libpq has some ability to cope with a v2 error message\neven when it's expecting v3. But I wouldn't bet on that being true of\nall client libraries, and anyway it's a very under-tested code path.\n\nSo I think we'd better go with the simple fix I showed before.\nIt's simple enough that maybe we could back-patch it, once it's\naged awhile in HEAD. OTOH, given the lack of field reports of\ntrouble here, I'm not sure back-patching is worth the risk.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 11 Sep 2020 11:52:55 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "Hi,\n\nOn 2020-09-11 11:52:55 -0400, Tom Lane wrote:\n> It's simple enough that maybe we could back-patch it, once it's\n> aged awhile in HEAD. OTOH, given the lack of field reports of\n> trouble here, I'm not sure back-patching is worth the risk.\n\nFWIW, looking at collected stack traces in azure, there's a slow but steady\nstream of crashes below StartupPacketTimeoutHandler. Most seem to be things\nlike\nlibcrypto->malloc->StartupPacketTimeoutHandler->proc_exit->socket_close->free->crash\nthere's a few other variants, some where the stack apparently was not\ndecipherable for the relevant tooling.\n\nNote that this wouldn't even include cases where this caused hangs - which is\nquite common IME.\n\n\nUnsurprisingly just in versions before 14, where this change went in.\n\nI think that might be enough evidence for backpatching the commit? I've not\nheard of issues due to the checks in check_on_shmem_exit_lists_are_empty().\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 2 Aug 2023 09:25:50 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On 2020-09-11 11:52:55 -0400, Tom Lane wrote:\n>> It's simple enough that maybe we could back-patch it, once it's\n>> aged awhile in HEAD. OTOH, given the lack of field reports of\n>> trouble here, I'm not sure back-patching is worth the risk.\n\n> FWIW, looking at collected stack traces in azure, there's a slow but steady\n> stream of crashes below StartupPacketTimeoutHandler. ...\n> Unsurprisingly just in versions before 14, where this change went in.\n> I think that might be enough evidence for backpatching the commit? I've not\n> heard of issues due to the checks in check_on_shmem_exit_lists_are_empty().\n\nI'd be willing to take a look at this in a few weeks when $real_life\nis a bit less demanding. Right before minor releases would likely be\na bad idea anyway.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 02 Aug 2023 12:35:19 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: SIGQUIT handling, redux" }, { "msg_contents": "Hi,\n\nOn 2023-08-02 12:35:19 -0400, Tom Lane wrote:\n> Andres Freund <andres@anarazel.de> writes:\n> > On 2020-09-11 11:52:55 -0400, Tom Lane wrote:\n> >> It's simple enough that maybe we could back-patch it, once it's\n> >> aged awhile in HEAD. OTOH, given the lack of field reports of\n> >> trouble here, I'm not sure back-patching is worth the risk.\n> \n> > FWIW, looking at collected stack traces in azure, there's a slow but steady\n> > stream of crashes below StartupPacketTimeoutHandler. ...\n> > Unsurprisingly just in versions before 14, where this change went in.\n> > I think that might be enough evidence for backpatching the commit? I've not\n> > heard of issues due to the checks in check_on_shmem_exit_lists_are_empty().\n> \n> I'd be willing to take a look at this in a few weeks when $real_life\n> is a bit less demanding.\n\nCool.\n\n\n> Right before minor releases would likely be a bad idea anyway.\n\nAgreed. I had just waded through the stacks, so I thought it'd be worth\nbringing up, didn't intend to imply we should backpatch immediately.\n\n\nAside: Analyzing this kind of thing at scale is made considerably more painful\nby \"expected\" ereport(PANIC)s (say out of disk space during WAL writes)\ncalling abort() and dumping core... While there are other PANICs you really\nwant cores of.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 2 Aug 2023 09:48:40 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: SIGQUIT handling, redux" } ]
[ { "msg_contents": "Hi,\n\nAttached is a patch to standardize Japanese names as given-name-first\nin the v13 contributors list as before.\n\nBest regards,\nEtsuro Fujita", "msg_date": "Wed, 9 Sep 2020 14:15:04 +0900", "msg_from": "Etsuro Fujita <etsuro.fujita@gmail.com>", "msg_from_op": true, "msg_subject": "Inconsistent Japanese name order in v13 contributors list" }, { "msg_contents": "\n\nOn 2020/09/09 14:15, Etsuro Fujita wrote:\n> Hi,\n> \n> Attached is a patch to standardize Japanese names as given-name-first\n> in the v13 contributors list as before.\n\nUsing given-name-first order is our consensus? I was thinking we have not\nreached that yet and our \"vague\" consensus was to use the name that each\ncontributor prefers, for example the name that used in the email signature, etc.\n\nBTW, if possible I'd like to use family-name-first, i.e., \"Fujii Masao\".\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Wed, 9 Sep 2020 14:40:12 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Inconsistent Japanese name order in v13 contributors list" }, { "msg_contents": "From: Fujii Masao <masao.fujii@oss.nttdata.com>\r\n> On 2020/09/09 14:15, Etsuro Fujita wrote:\r\n> > Attached is a patch to standardize Japanese names as given-name-first\r\n> > in the v13 contributors list as before.\r\n> \r\n> Using given-name-first order is our consensus? I was thinking we have not\r\n> reached that yet and our \"vague\" consensus was to use the name that each\r\n> contributor prefers, for example the name that used in the email signature, etc.\r\n> \r\n> BTW, if possible I'd like to use family-name-first, i.e., \"Fujii Masao\".\r\n\r\nAccording to the following article, first name -> given name order is usually used even for Western personal names? I don't mind either way. What I hope is to not burdon people who author the release note page.\r\n\r\n\r\nPersonal name - Wikipedia\r\nhttps://en.wikipedia.org/wiki/Personal_name\r\n\r\n\"Western name order\"\r\n\r\n\"Within alphabetic lists and catalogs, however, the family name is generally put first, with the given name(s) following, separated from it by a comma (e.g. Smith, John), representing the \"lexical name order\". This convention is followed by most Western libraries, as well as on many administrative forms.\"\r\n\r\n\r\nRegards\r\nTakayuki Tsunakawa\r\n\t\r\n\r\n", "msg_date": "Wed, 9 Sep 2020 05:58:10 +0000", "msg_from": "\"tsunakawa.takay@fujitsu.com\" <tsunakawa.takay@fujitsu.com>", "msg_from_op": false, "msg_subject": "RE: Inconsistent Japanese name order in v13 contributors list" }, { "msg_contents": "On Wed, Sep 9, 2020 at 2:58 PM tsunakawa.takay@fujitsu.com\n<tsunakawa.takay@fujitsu.com> wrote:\n> From: Fujii Masao <masao.fujii@oss.nttdata.com>\n> > On 2020/09/09 14:15, Etsuro Fujita wrote:\n> > > Attached is a patch to standardize Japanese names as given-name-first\n> > > in the v13 contributors list as before.\n> >\n> > Using given-name-first order is our consensus?\n\nNot sure. I did so just as before.\n\n> > BTW, if possible I'd like to use family-name-first, i.e., \"Fujii Masao\".\n\n> \"Within alphabetic lists and catalogs, however, the family name is generally put first, with the given name(s) following, separated from it by a comma (e.g. Smith, John), representing the \"lexical name order\". This convention is followed by most Western libraries, as well as on many administrative forms.\"\n\nI think it would be a good idea to use this convention because that\nmakes clear which one is his/her given name.\n\nBest regards,\nEtsuro Fujita\n\n\n", "msg_date": "Wed, 9 Sep 2020 15:16:20 +0900", "msg_from": "Etsuro Fujita <etsuro.fujita@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Inconsistent Japanese name order in v13 contributors list" }, { "msg_contents": "On Tue, Sep 8, 2020 at 10:15 PM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:\n> Attached is a patch to standardize Japanese names as given-name-first\n> in the v13 contributors list as before.\n\nI recently read that the Japanese government issued a decree about this:\n\nhttps://www.economist.com/asia/2020/01/02/why-japanese-names-have-flipped\n\nIn my opinion the Japanese practice of family name first is not\nconfusing in any way. However, it can be confusing when it is applied\ninconsistently.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Tue, 8 Sep 2020 23:35:58 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: Inconsistent Japanese name order in v13 contributors list" }, { "msg_contents": "On 2020-09-09 07:40, Fujii Masao wrote:\n>> Attached is a patch to standardize Japanese names as given-name-first\n>> in the v13 contributors list as before.\n> \n> Using given-name-first order is our consensus? I was thinking we have not\n> reached that yet and our \"vague\" consensus was to use the name that each\n> contributor prefers, for example the name that used in the email signature, etc.\n> \n> BTW, if possible I'd like to use family-name-first, i.e., \"Fujii Masao\".\n\nSee commit 53c89aed7b38ab412fddc1d6118822ce5d962acd for when this was \nchanged.\n\nAt least it's the current practice. It can be debated whether it's a \ngood practice.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 9 Sep 2020 14:15:39 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Inconsistent Japanese name order in v13 contributors list" }, { "msg_contents": "On 2020-09-09 07:15, Etsuro Fujita wrote:\n> Attached is a patch to standardize Japanese names as given-name-first\n> in the v13 contributors list as before.\n\nGiven existing practice, this patch looks okay.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 9 Sep 2020 14:16:51 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Inconsistent Japanese name order in v13 contributors list" }, { "msg_contents": "\n\nOn 2020/09/09 21:15, Peter Eisentraut wrote:\n> On 2020-09-09 07:40, Fujii Masao wrote:\n>>> Attached is a patch to standardize Japanese names as given-name-first\n>>> in the v13 contributors list as before.\n>>\n>> Using given-name-first order is our consensus? I was thinking we have not\n>> reached that yet and our \"vague\" consensus was to use the name that each\n>> contributor prefers, for example the name that used in the email signature, etc.\n>>\n>> BTW, if possible I'd like to use family-name-first, i.e., \"Fujii Masao\".\n> \n> See commit 53c89aed7b38ab412fddc1d6118822ce5d962acd for when this was changed.\n> \n> At least it's the current practice.  It can be debated whether it's a good practice.\n\nThanks for letting me know that! Ok, using family-name-first rule only\nfor me would make the maintain of contributors list harder, so I'm ok\nto follow the given-name-first rule for the list.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 10 Sep 2020 01:37:11 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Inconsistent Japanese name order in v13 contributors list" }, { "msg_contents": "On 2020-Sep-09, Fujii Masao wrote:\n\n> On 2020/09/09 14:15, Etsuro Fujita wrote:\n> > Hi,\n> > \n> > Attached is a patch to standardize Japanese names as given-name-first\n> > in the v13 contributors list as before.\n> \n> Using given-name-first order is our consensus? I was thinking we have not\n> reached that yet and our \"vague\" consensus was to use the name that each\n> contributor prefers, for example the name that used in the email signature, etc.\n\nThat's indeed our historical practice. See previous thread where we've\ndiscussed this at length,\nhttps://www.postgresql.org/message-id/flat/20150613231826.GY133018%40postgresql.org#88d245a5cdd2b32e1e3e80fc07eab6f2\n\nThe Economist piece Peter G cited is also relevant.\n\nThe commit Peter E cited seems more anecdotical than precedence-setting,\nsince there was no actual discussion, and whatever little there was was\nconfined to pgsql-committers.\n\n\nAn easy way to avoid any confusion is to uppercase the family name in\nthe cases where it goes first.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 9 Sep 2020 15:27:42 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Inconsistent Japanese name order in v13 contributors list" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> On 2020-Sep-09, Fujii Masao wrote:\n>> Using given-name-first order is our consensus?\n\n> That's indeed our historical practice. See previous thread where we've\n> discussed this at length,\n> https://www.postgresql.org/message-id/flat/20150613231826.GY133018%40postgresql.org#88d245a5cdd2b32e1e3e80fc07eab6f2\n\n> The Economist piece Peter G cited is also relevant.\n\nRight. I think the decree the Economist cites might be sufficient\nreason to reopen the discussion, though I surely don't want it to\nturn into another long thread.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 09 Sep 2020 14:42:41 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Inconsistent Japanese name order in v13 contributors list" }, { "msg_contents": "On Wed, Sep 9, 2020 at 9:16 PM Peter Eisentraut\n<peter.eisentraut@2ndquadrant.com> wrote:\n> On 2020-09-09 07:15, Etsuro Fujita wrote:\n> > Attached is a patch to standardize Japanese names as given-name-first\n> > in the v13 contributors list as before.\n>\n> Given existing practice, this patch looks okay.\n\nI've applied the patch. Thanks for the review!\n\nBest regards,\nEtsuro Fujita\n\n\n", "msg_date": "Thu, 10 Sep 2020 16:25:48 +0900", "msg_from": "Etsuro Fujita <etsuro.fujita@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Inconsistent Japanese name order in v13 contributors list" }, { "msg_contents": "On Wed, Sep 9, 2020 at 03:27:42PM -0300, Alvaro Herrera wrote:\n> On 2020-Sep-09, Fujii Masao wrote:\n> \n> > On 2020/09/09 14:15, Etsuro Fujita wrote:\n> > > Hi,\n> > > \n> > > Attached is a patch to standardize Japanese names as given-name-first\n> > > in the v13 contributors list as before.\n> > \n> > Using given-name-first order is our consensus? I was thinking we have not\n> > reached that yet and our \"vague\" consensus was to use the name that each\n> > contributor prefers, for example the name that used in the email signature, etc.\n> \n> That's indeed our historical practice. See previous thread where we've\n> discussed this at length,\n> https://www.postgresql.org/message-id/flat/20150613231826.GY133018%40postgresql.org#88d245a5cdd2b32e1e3e80fc07eab6f2\n> \n> The Economist piece Peter G cited is also relevant.\n> \n> The commit Peter E cited seems more anecdotical than precedence-setting,\n> since there was no actual discussion, and whatever little there was was\n> confined to pgsql-committers.\n\nThis thread from 2015 is the most comprehensive discussion I remember of\nJapanese name ordering, including a suggestion to use small caps:\n\n\thttps://www.postgresql.org/message-id/flat/20150613231826.GY133018%40postgresql.org#88d245a5cdd2b32e1e3e80fc07eab6f2\n\nI have been following this guidance ever since.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Fri, 18 Sep 2020 18:18:11 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Inconsistent Japanese name order in v13 contributors list" }, { "msg_contents": "On 2020-Sep-18, Bruce Momjian wrote:\n\n> This thread from 2015 is the most comprehensive discussion I remember of\n> Japanese name ordering, including a suggestion to use small caps:\n> \n> \thttps://www.postgresql.org/message-id/flat/20150613231826.GY133018%40postgresql.org#88d245a5cdd2b32e1e3e80fc07eab6f2\n> \n> I have been following this guidance ever since.\n\nRight.\n\nAbout smallcaps, we didn't do it then because there was no way known to\nus to use them in our then-current toolchain. But we've changed now to\nXML and apparently it is possible to use them -- we could try something\nlike <emphasis role=\"caps_lastname\"> and define a CSS rule like\n\n.caps_lastname {font-variant: small-caps;}\n\n(Apparently you also need to set 'emphasis.propagates.style' to 1 in the\nstylesheet). This does it for HTML. You also need some FO trick to\ncover the PDF (probably something like what a042750646db did to change\ncatalog_table_entry formatting.)\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 21 Sep 2020 10:31:31 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Inconsistent Japanese name order in v13 contributors list" }, { "msg_contents": "On Mon, Sep 21, 2020 at 10:31:31AM -0300, Alvaro Herrera wrote:\n> On 2020-Sep-18, Bruce Momjian wrote:\n> \n> > This thread from 2015 is the most comprehensive discussion I remember of\n> > Japanese name ordering, including a suggestion to use small caps:\n> > \n> > \thttps://www.postgresql.org/message-id/flat/20150613231826.GY133018%40postgresql.org#88d245a5cdd2b32e1e3e80fc07eab6f2\n> > \n> > I have been following this guidance ever since.\n> \n> Right.\n> \n> About smallcaps, we didn't do it then because there was no way known to\n> us to use them in our then-current toolchain. But we've changed now to\n> XML and apparently it is possible to use them -- we could try something\n> like <emphasis role=\"caps_lastname\"> and define a CSS rule like\n> \n> .caps_lastname {font-variant: small-caps;}\n\nYes, that's what I use for CSS.\n\n> (Apparently you also need to set 'emphasis.propagates.style' to 1 in the\n> stylesheet). This does it for HTML. You also need some FO trick to\n> cover the PDF (probably something like what a042750646db did to change\n> catalog_table_entry formatting.)\n\nYeah, we have PDF output to worry about too. It is easy in LaTeX.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Thu, 24 Sep 2020 16:31:55 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Inconsistent Japanese name order in v13 contributors list" } ]
[ { "msg_contents": "Here is a patch for minor cleanup of the partbounds.c changes made by\ncommit c8434d64c: 1) removes a useless assignment (in normal builds)\nand 2) improves comments a little.\n\nBest regards,\nEtsuro Fujita", "msg_date": "Wed, 9 Sep 2020 22:37:07 +0900", "msg_from": "Etsuro Fujita <etsuro.fujita@gmail.com>", "msg_from_op": true, "msg_subject": "Minor cleanup of partbounds.c" }, { "msg_contents": "On 2020-Sep-09, Etsuro Fujita wrote:\n\n> Here is a patch for minor cleanup of the partbounds.c changes made by\n> commit c8434d64c: 1) removes a useless assignment (in normal builds)\n\nLGTM.\n\n> and 2) improves comments a little.\n\nNo objection to changing \"bounds\" to \"range bounds\".\n\nI think the point other is to replace the only appearance of \"dummy\nrelation\" to better match the extensive use of \"dummy partition\" in this\nfile. The concept of a \"dummy relation\" is well established in the\nplanner. I didn't know if \"dummy partition\" is itself a concept\n(apparently in the newfangled partition-wise join stuff), or just\nglorified wording to say \"a dummy relation that happens to be a\npartition\". Looking at is_dummy_partition, apparently a dummy partition\nis either a dummy relation or a partition that doesn't have a\nRelOptInfo. So my conclusion is that this wording is okay to change\ntoo.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 9 Sep 2020 14:05:05 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Minor cleanup of partbounds.c" }, { "msg_contents": "On Thu, Sep 10, 2020 at 2:05 AM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n> On 2020-Sep-09, Etsuro Fujita wrote:\n> > Here is a patch for minor cleanup of the partbounds.c changes made by\n> > commit c8434d64c: 1) removes a useless assignment (in normal builds)\n>\n> LGTM.\n>\n> > and 2) improves comments a little.\n>\n> No objection to changing \"bounds\" to \"range bounds\".\n>\n> I think the point other is to replace the only appearance of \"dummy\n> relation\" to better match the extensive use of \"dummy partition\" in this\n> file. The concept of a \"dummy relation\" is well established in the\n> planner. I didn't know if \"dummy partition\" is itself a concept\n> (apparently in the newfangled partition-wise join stuff), or just\n> glorified wording to say \"a dummy relation that happens to be a\n> partition\". Looking at is_dummy_partition, apparently a dummy partition\n> is either a dummy relation or a partition that doesn't have a\n> RelOptInfo. So my conclusion is that this wording is okay to change\n> too.\n\nCool!\n\nI pushed the patch. Thanks for reviewing!\n\nBest regards,\nEtsuro Fujita\n\n\n", "msg_date": "Thu, 10 Sep 2020 18:10:37 +0900", "msg_from": "Etsuro Fujita <etsuro.fujita@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Minor cleanup of partbounds.c" } ]
[ { "msg_contents": "Hello hackers,\n\nPlease consider fixing minor defects in the source code and documentation.\n1. a missing dot in guc.c\n\"SELECT name, short_desc FROM pg_settings WHERE short_desc NOT LIKE\n'%.'\" finds only this one instance.\n2. inrange -> in_range\nthe former spelling is unique\n3. sigature -> signature\n4. \"start timeline %u not found history of timeline %u\" -> \"start\ntimeline %u not found in history of timeline %u\"\nit seems that a preposition is missing\n5. <type>BackgroundWorker *worker</type> -> <parameter>BackgroundWorker\n*worker</parameter>\nincorrect Docbook tag\n6. \"unhandled previous state in xqs\" -> \"unhandled previous state at end\nquote\"?\n\"xqs\" is rather cryptic for a user-visible message\n\nI'm not sure about 6, so the attached patch covers only 1-5.\n\nBest regards,\nAlexander", "msg_date": "Wed, 9 Sep 2020 17:00:00 +0300", "msg_from": "Alexander Lakhin <exclusion@gmail.com>", "msg_from_op": true, "msg_subject": "Minor fixes for upcoming version 13" }, { "msg_contents": "Alexander Lakhin <exclusion@gmail.com> writes:\n> Please consider fixing minor defects in the source code and documentation.\n\nI agree with all of these, except the markup fixes in bgworker.sgml\nstill seem not right; it should be more like\n\n <function>RegisterBackgroundWorker(<type>BackgroundWorker</type> *<parameter>worker</parameter>)</function>\n\n> 6. \"unhandled previous state in xqs\" -> \"unhandled previous state at end\n> quote\"?\n> \"xqs\" is rather cryptic for a user-visible message\n\nBut it's not user-visible is it? That should surely be a can't-happen\ncase.\n\nWill push in a little bit.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 09 Sep 2020 11:29:18 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Minor fixes for upcoming version 13" }, { "msg_contents": "Hello Tom,\n\n09.09.2020 18:29, Tom Lane wrote:\n> Alexander Lakhin <exclusion@gmail.com> writes:\n>> Please consider fixing minor defects in the source code and documentation.\n> I agree with all of these, except the markup fixes in bgworker.sgml\n> still seem not right; it should be more like\n>\n> <function>RegisterBackgroundWorker(<type>BackgroundWorker</type> *<parameter>worker</parameter>)</function>\nYes, but I've tried to minimize the change and align with the adjacent\ntext. For example:\n<para>Once running, the process can connect to a database by calling\n   <function>BackgroundWorkerInitializeConnection(<parameter>char\n*dbname</parameter>...\n>> 6. \"unhandled previous state in xqs\" -> \"unhandled previous state at end\n>> quote\"?\n>> \"xqs\" is rather cryptic for a user-visible message\n> But it's not user-visible is it? That should surely be a can't-happen\n> case.\nI've encountered this while translating NLS messages in postgres.po and\necpg.po. So I think it should at least puzzle translators.\n\nBest regards,\nAlexander\n\n\n", "msg_date": "Wed, 9 Sep 2020 19:16:16 +0300", "msg_from": "Alexander Lakhin <exclusion@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Minor fixes for upcoming version 13" }, { "msg_contents": "On Wed, Sep 9, 2020 at 12:16 PM Alexander Lakhin <exclusion@gmail.com> wrote:\n>\n> Hello Tom,\n>\n> 09.09.2020 18:29, Tom Lane wrote:\n> > But it's not user-visible is it? That should surely be a can't-happen\n> > case.\n> I've encountered this while translating NLS messages in postgres.po and\n> ecpg.po. So I think it should at least puzzle translators.\n\nMaybe instead Assert(0) with a comment or something like that?\n\n-- \nJohn Naylor https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 9 Sep 2020 12:20:32 -0400", "msg_from": "John Naylor <john.naylor@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Minor fixes for upcoming version 13" }, { "msg_contents": "John Naylor <john.naylor@2ndquadrant.com> writes:\n> On Wed, Sep 9, 2020 at 12:16 PM Alexander Lakhin <exclusion@gmail.com> wrote:\n>> 09.09.2020 18:29, Tom Lane wrote:\n>>> But it's not user-visible is it? That should surely be a can't-happen\n>>> case.\n\n>> I've encountered this while translating NLS messages in postgres.po and\n>> ecpg.po. So I think it should at least puzzle translators.\n\n> Maybe instead Assert(0) with a comment or something like that?\n\nMaybe what we need is yyerror_internal() for messages that don't require\ntranslation. Or just convert it to a plain elog(ERROR) ... that would\nlose the possibility of providing an error cursor, but that seems like\nsomething we don't need here either.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 09 Sep 2020 12:26:28 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Minor fixes for upcoming version 13" } ]
[ { "msg_contents": "Also, the behavior (=line of code) added by the bug fix is the same as existing code in the same function, _bt_first(), at lines 898, 1096, 1132, 1367. And the calls to _bt_parallel_readpage(), line 903, and _bt_steppage(), line 1416, will also ultimately call _bt_parallel_done(). So the bug seems to be a pretty simple oversight: in 6 out of 7 cases in _bt_first(), we call _bt_parallel_done() before returning \"false\"; but in the 7th case (fixed in this bug fix), we do not. The fix is to make case #7 the same as the other 6.\r\n\r\nJames\r\n\r\nOn 9/9/20, 7:11 AM, \"Jameson, Hunter 'James'\" <hunjmes@amazon.com> wrote:\r\n\r\n Hi, I spent some time trying to create a repro (other than testing it on the production instance where we encountered the bug), but was unable to create one within a reasonable time.\r\n\r\n The tricky part is that the bug symptoms are run-time symptoms -- so not only do you need, first, to satisfy conditions (1), (2), and (3), without the query optimizer optimizing them away! -- but you also need, second, a query that runs long enough for one or more of the parallel workers' state machines to get confused. (This wasn't a problem on the production instance where we encountered the bug and I tested the fix.)\r\n\r\n Also, third-- passing InvalidBlockNumber to ReadBuffer() generally just appends a new block to the relation, so the bug doesn't even result in an error condition on an RW instance. (The production instance was RO...) So the bug, although very small!, is annoying!\r\n\r\n James\r\n\r\n On 9/9/20, 6:14 AM, \"Amit Kapila\" <amit.kapila16@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, Sep 8, 2020 at 11:55 PM Jameson, Hunter 'James'\r\n <hunjmes@amazon.com> wrote:\r\n >\r\n > Hi, I ran across a small (but annoying) bug in initializing parallel BTree scans, which causes the parallel-scan state machine to get confused.\r\n >\r\n >\r\n > To reproduce, you need a query that:\r\n >\r\n >\r\n >\r\n > 1. Executes parallel BTree index scan;\r\n >\r\n > 2. Has an IN-list of size > 1;\r\n >\r\n > 3. Has an additional index filter that makes it impossible to satisfy the\r\n >\r\n > first IN-list condition.\r\n >\r\n >\r\n >\r\n > (We encountered such a query, and therefore the bug, on a production instance.)\r\n >\r\n >\r\n\r\n I think I can understand what you are pointing out here but it would\r\n be great if you can have a reproducible test case because that will\r\n make it apparent and we might want to include that in the regression\r\n tests if possible.\r\n\r\n --\r\n With Regards,\r\n Amit Kapila.\r\n\r\n\r\n", "msg_date": "Wed, 9 Sep 2020 14:35:18 +0000", "msg_from": "\"Jameson, Hunter 'James'\" <hunjmes@amazon.com>", "msg_from_op": true, "msg_subject": "Re: [UNVERIFIED SENDER] Re: Fix for parallel BTree initialization bug" } ]
[ { "msg_contents": "Hi all\n\nAs I've gained experience working on background workers, it's become\nincreasingly clear that they're a bit too different to normal backends for\nmany nontrivial uses.\n\nI thought I'd take a moment to note some of it here, along with some\nproposals for things we could potentially do to make it much easier to use\nbgworkers correctly especially when using them to run queries.\n\nThis is NOT A PATCH SET. It's a set of discussion proposals and it's also\nintended as a bit of a helper for people just getting started on bgworkers.\nThere are a lot of subtle differences in the runtime environment a basic\nbgworker provides vs the runtime environment extension authors will be used\nto when writing fmgr-callable C functions.\n\n(It looks like pg12 and pg13 have some improvements, so some of the issues\nI was going to mention with error cleanup paths and locking aren't relevant\nanymore.)\n\nDIFFERENCES WHEN CODING FOR BGWORKERS\n----\n\nSome of the most important differences vs normal backends that I've noticed\nare:\n\n* There's no supported way to recover from an error and continue execution.\nEach bgworker has to roll its own logic based on PostgresMain()'s\nsigsetjmp() handler and maintain it.\n* The bgworker infrastructure doesn't set up the the application_name in\nPGPROC\n* Example bgworkers roll their own signal handlers rather than using die,\nprocsignal_sigusr1_handler, and PostgresSigHupHandler. This makes them seem\nto work OK, but fail to respect CHECK_FOR_INTERRUPTS() and other expected\nbehaviour when they call into the executor etc.\n* Each bgworker has to roll its own mainloop with ConfigReloadPending /\nProcessConfigFile() etc, and this isn't illustrated at all in the examples\n* Example workers don't interact with the pgstat subsystem\n\nManaging bgworker lifecycle is also quite difficult. The postmaster doesn't\noffer any help and we don't expose much help from core. Any extension that\nspawns workers needs to do its own handling of worker startup registration\nin shmem, worker exit reaping, handling workers that exit before\nregistering, etc. This can be seen in the logical replication code, which\nrolls its own management per src/backend/replication/logical/launcher.c .\n\nPROPOSED CHANGES IN EXAMPLE BGWORKERS/CONTRIBS\n-----\n\nSo I'd like to make these changes to example bgworkers and to contrib\nextensions:\n\n* Change example bgworkers in contrib to set up normal default signal\nhandlers, not define their own\n* Add ConfigReloadPending and ProcessConfigFile() to all example bgworkers\n* Show pgstat use in example bgworkers\n\nPROPOSED BGW SETUP AND MAINLOOP HELPERS\n----\n\nand I'm wondering if anyone thinks it's a good idea to add some bgworker\nmainloop helper API, where one call is made at the start of the bgw, before\nBackgroundWorkerInitializeConnection(), to:\n\n* set application_name\n* set process title\n* set up default signal handlers and unblock signals\n* creates and assigns a BGWMemoryContext named after the bgw\n* set state to idle in pgstat\n* sets up MyProcPort (or teach InitPostgres to do so for a bgw)\n* takes a function pointer for a before_shmem_exit cleanup handler\n to encourage ext authors to use this approach\n\nthen a mainloop helper that:\n\n* Checks that CurrentMemoryContext == BGWMemoryContext\n* Runs CHECK_FOR_INTERRUPTS()\n* Checks for postmaster death and exits\n* Checks for and performs config file reload\n\n\n\nPROPOSED ERROR HANDLING HELPER\n----\n\nIt'd also be beneficial to have a helper for bgw mainloops with error\nrecovery, generalizing and extracting the pattern I see in all these\nroutines:\n\nsrc/backend/postmaster/autovacuum.c=AutoVacLauncherMain\nsrc/backend/postmaster/autovacuum.c=AutoVacWorkerMain\nsrc/backend/postmaster/bgworker.c=StartBackgroundWorker\nsrc/backend/postmaster/bgwriter.c=BackgroundWriterMain\nsrc/backend/postmaster/checkpointer.c=CheckpointerMain\nsrc/backend/postmaster/walwriter.c=WalWriterMain\nsrc/backend/tcop/postgres.c=PostgresMain\n\nwhich all do their own error reset loops. There's way too much copy/paste\ngoing on there IMO, even before we consider bgworkers, and it's nearly\nimpossible for anyone who isn't quite an experienced Pg developer to write\na bgw that can do anything with errors except promote ERROR to FATAL and\ndie.\n\nThis would be modeled on PosgresMain(). The worker would only need to add\nits own logic to the sigsetjmp() error jump path, not duplicate all the\ncore cleanup work.\n\nPROPOSED GENERALISED WORKER MANAGEMENT\n----\n\nFinally I'm wondering if there's any interest in generalizing the logical\nrep worker management for other bgworkers. I've done a ton of work with\nworker management and it's something I'm sure I could take on but I don't\nwant to write it without knowing there's some chance of acceptance.\n\nThe general idea is to provide a way for bgworkers to start up managers for\npools / sets of workers. They launch them and have a function they can call\nin their mainloop that watches their child worker states, invoking\ncallbacks when they fail to launch, launch successfully, exit cleanly after\nfinishing their work, or die with an error. Workers are tracked in a shmem\nseg where the start of the seg must be a key struct (akin to how the hash\nAPI works). We would provide calls to look up a worker shmem struct by key,\nsignal a worker by key, wait for a worker to exit (up to timeout), etc.\nLike in the logical rep code, access to the worker registration shmem would\nbe controlled by LWLock. The extension code can put whatever it wants in\nthe worker shmem entries after the key, including various unions or\nwhatever - the worker management API won't care.\n\nThis abstracts all the low level mess away from bgworker implementations\nand lets them focus on writing the code they want to run.\n\nI'd probably suggest doing so by extracting the logical rep worker\nmanagement, and making the logical rep code use the generalized worker\nmanagement. So it'd be proven, and have in core users.\n\nPROPOSED XACT API WRAPPER\n----\n\nAdditionally there are some more general postgres API patterns that the\nteam working on pglogical and BDR has landed up writing wrappers for or\ncompensating for. One of the most important is transaction management. In\nmany places in pglogical where we start lightweight transactions in\npglogical we use a wrapper that starts the txn if there isn't already one\nopen and remembers whether one was started. Then the end helper closes it\nonly if the start helper opened it. Finally, the memory context is always\nreset to the memory context before txn start once the txn ends, instead of\nbeing left at TopMemoryContext, since we've learned that that's an\nextremely common source of bugs.\n\nI propose a wrapper for lightweight txn management, like the one we use in\nmany places in pglogical. This is not a copy of that code, it's just a\nscratched out example of roughly how we do it:\n\nLocalTransactionState txn;\nStartTransactionIfNotStarted(&txn, LXACT_WANT_SNAPSHOT);\n...\nCommitTransactionCommandIfStarted(&txn);\n\nwhere\n\nstatic inline void\nStartTransactionIfNotStarted(LocalTransactionState *txn, int flags)\n{\n txn->started = !TransactionInProgress();\n txn->save_mctx = CurrentMemoryContext;\n if (txn->started)\n {\n txn->pushed_snapshot = false;\n StartTransactionCommand();\n if (flags & LXACT_WANT_SNAPSHOT)\n {\n txn->pushed_snapshot = true;\n PushActiveSnapshot(GetTransactionSnapshot());\n }\n }\n}\n\nstatic inline void\nCommitTransactionIfNotStarted(LocalTransactionState *txn)\n{\n if (txn->started)\n {\n Assert(TransactionInProgress());\n Assert(CurrentMemoryContext == TopTransactionContext);\n if (txn->pushed_snapshot)\n PopActiveSnapshot();\n CommitTransactionCommand();\n }\n else\n {\n /* Caller didn't change context between start and end */\n Assert(CurrentMemoryContext == txn->save_mctx);\n }\n (void) MemoryContextSwitchTo(txn->save_mctx);\n}\n\n-- \n Craig Ringer http://www.2ndQuadrant.com/\n 2ndQuadrant - PostgreSQL Solutions for the Enterprise\n\nHi allAs I've gained experience working on background workers, it's become increasingly clear that they're a bit too different to normal backends for many nontrivial uses.I thought I'd take a moment to note some of it here, along with some proposals for things we could potentially do to make it much easier to use bgworkers correctly especially when using them to run queries.This is NOT A PATCH SET. It's a set of discussion proposals and it's also intended as a bit of a helper for people just getting started on bgworkers. There are a lot of subtle differences in the runtime environment a basic bgworker provides vs the runtime environment extension authors will be used to when writing fmgr-callable C functions.(It looks like pg12 and pg13 have some improvements, so some of the issues I was going to mention with error cleanup paths and locking aren't relevant anymore.)DIFFERENCES WHEN CODING FOR BGWORKERS----Some of the most important differences vs normal backends that I've noticed are:* There's no supported way to recover from an error and continue execution. Each bgworker has to roll its own logic based on PostgresMain()'s sigsetjmp() handler and maintain it.* The bgworker infrastructure doesn't set up the the  application_name in PGPROC* Example bgworkers roll their own signal handlers rather than using die, procsignal_sigusr1_handler, and PostgresSigHupHandler. This makes them seem to work OK, but fail to respect CHECK_FOR_INTERRUPTS() and other expected behaviour when they call into the executor etc.* Each bgworker has to roll its own mainloop with ConfigReloadPending / ProcessConfigFile() etc, and this isn't illustrated at all in the examples* Example workers don't interact with the pgstat subsystemManaging bgworker lifecycle is also quite difficult. The postmaster doesn't offer any help and we don't expose much help from core. Any extension that spawns workers needs to do its own handling of worker startup registration in shmem, worker exit reaping, handling workers that exit before registering, etc. This can be seen in the logical replication code, which rolls its own management per src/backend/replication/logical/launcher.c .PROPOSED CHANGES IN EXAMPLE BGWORKERS/CONTRIBS-----So I'd like to make these changes to example bgworkers and to contrib extensions:* Change example bgworkers in contrib to set up normal default signal handlers, not define their own* Add ConfigReloadPending and ProcessConfigFile() to all example bgworkers* Show pgstat use in example bgworkersPROPOSED BGW SETUP AND MAINLOOP HELPERS ----and I'm wondering if anyone thinks it's a good idea to add some bgworker mainloop helper API, where one call is made at the start of the bgw, before BackgroundWorkerInitializeConnection(), to:* set application_name* set process title* set up default signal handlers and unblock signals* creates and assigns a BGWMemoryContext named after the bgw* set state to idle in pgstat* sets up MyProcPort (or teach InitPostgres to do so for a bgw)* takes a function pointer for a before_shmem_exit cleanup handler  to encourage ext authors to use this approachthen a mainloop helper that:* Checks that CurrentMemoryContext == BGWMemoryContext* Runs CHECK_FOR_INTERRUPTS() * Checks for postmaster death and exits* Checks for and performs config file reloadPROPOSED ERROR HANDLING HELPER----It'd also be beneficial to have a helper for bgw mainloops with error recovery, generalizing and extracting the pattern I see in all these routines:src/backend/postmaster/autovacuum.c=AutoVacLauncherMainsrc/backend/postmaster/autovacuum.c=AutoVacWorkerMainsrc/backend/postmaster/bgworker.c=StartBackgroundWorkersrc/backend/postmaster/bgwriter.c=BackgroundWriterMainsrc/backend/postmaster/checkpointer.c=CheckpointerMainsrc/backend/postmaster/walwriter.c=WalWriterMainsrc/backend/tcop/postgres.c=PostgresMainwhich all do their own error reset loops. There's way too much copy/paste going on there IMO, even before we consider bgworkers, and it's nearly impossible for anyone who isn't quite an experienced Pg developer to write a bgw that can do anything with errors except promote ERROR to FATAL and die.This would be modeled on PosgresMain(). The worker would only need to add its own logic to the sigsetjmp() error jump path, not duplicate all the core cleanup work.PROPOSED GENERALISED WORKER MANAGEMENT---- Finally I'm wondering if there's any interest in generalizing the logical rep worker management for other bgworkers. I've done a ton of work with worker management and it's something I'm sure I could take on but I don't want to write it without knowing there's some chance of acceptance.The general idea is to provide a way for bgworkers to start up managers for pools / sets of workers. They launch them and have a function they can call in their mainloop that watches their child worker states, invoking callbacks when they fail to launch, launch successfully, exit cleanly after finishing their work, or die with an error. Workers are tracked in a shmem seg where the start of the seg must be a key struct (akin to how the hash API works). We would provide calls to look up a worker shmem struct by key, signal a worker by key, wait for a worker to exit (up to timeout), etc. Like in the logical rep code, access to the worker registration shmem would be controlled by LWLock. The extension code can put whatever it wants in the worker shmem entries after the key, including various unions or whatever - the worker management API won't care.This abstracts all the low level mess away from bgworker implementations and lets them focus on writing the code they want to run.I'd probably suggest doing so by extracting the logical rep worker management, and making the logical rep code use the generalized worker management. So it'd be proven, and have in core users.PROPOSED XACT API WRAPPER----Additionally there are some more general postgres API patterns that the team working on pglogical and BDR has landed up writing wrappers for or compensating for. One of the most important is transaction management. In many places in pglogical where we start lightweight transactions in pglogical we use a wrapper that starts the txn if there isn't already one open and remembers whether one was started. Then the end helper closes it only if the start helper opened it. Finally, the memory context is always reset to the memory context before txn start once the txn ends, instead of being left at TopMemoryContext, since we've learned that that's an extremely common source of bugs.I propose a wrapper for lightweight txn management, like the one we use in many places in pglogical. This is not a copy of that code, it's just a scratched out example of roughly how we do it:LocalTransactionState txn;StartTransactionIfNotStarted(&txn, LXACT_WANT_SNAPSHOT);...CommitTransactionCommandIfStarted(&txn);wherestatic inline voidStartTransactionIfNotStarted(LocalTransactionState *txn, int flags){    txn->started = !TransactionInProgress();    txn->save_mctx = CurrentMemoryContext;    if (txn->started)    {        txn->pushed_snapshot = false;        StartTransactionCommand();        if (flags & LXACT_WANT_SNAPSHOT)        {            txn->pushed_snapshot = true;            PushActiveSnapshot(GetTransactionSnapshot());        }    }}static inline voidCommitTransactionIfNotStarted(LocalTransactionState *txn){    if (txn->started)    {        Assert(TransactionInProgress());        Assert(CurrentMemoryContext == TopTransactionContext);        if (txn->pushed_snapshot)            PopActiveSnapshot();        CommitTransactionCommand();    }    else    {        /* Caller didn't change context between start and end */        Assert(CurrentMemoryContext == txn->save_mctx);    }    (void) MemoryContextSwitchTo(txn->save_mctx);}--  Craig Ringer                   http://www.2ndQuadrant.com/ 2ndQuadrant - PostgreSQL Solutions for the Enterprise", "msg_date": "Thu, 10 Sep 2020 11:02:07 +0800", "msg_from": "Craig Ringer <craig@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Proposals for making it easier to write correct bgworkers" }, { "msg_contents": "čt 10. 9. 2020 v 5:02 odesílatel Craig Ringer <craig@2ndquadrant.com>\nnapsal:\n\n> Hi all\n>\n> As I've gained experience working on background workers, it's become\n> increasingly clear that they're a bit too different to normal backends for\n> many nontrivial uses.\n>\n> I thought I'd take a moment to note some of it here, along with some\n> proposals for things we could potentially do to make it much easier to use\n> bgworkers correctly especially when using them to run queries.\n>\n> This is NOT A PATCH SET. It's a set of discussion proposals and it's also\n> intended as a bit of a helper for people just getting started on bgworkers.\n> There are a lot of subtle differences in the runtime environment a basic\n> bgworker provides vs the runtime environment extension authors will be used\n> to when writing fmgr-callable C functions.\n>\n> (It looks like pg12 and pg13 have some improvements, so some of the issues\n> I was going to mention with error cleanup paths and locking aren't relevant\n> anymore.)\n>\n> DIFFERENCES WHEN CODING FOR BGWORKERS\n> ----\n>\n> Some of the most important differences vs normal backends that I've\n> noticed are:\n>\n> * There's no supported way to recover from an error and continue\n> execution. Each bgworker has to roll its own logic based on\n> PostgresMain()'s sigsetjmp() handler and maintain it.\n> * The bgworker infrastructure doesn't set up the the application_name in\n> PGPROC\n> * Example bgworkers roll their own signal handlers rather than using die,\n> procsignal_sigusr1_handler, and PostgresSigHupHandler. This makes them seem\n> to work OK, but fail to respect CHECK_FOR_INTERRUPTS() and other expected\n> behaviour when they call into the executor etc.\n> * Each bgworker has to roll its own mainloop with ConfigReloadPending /\n> ProcessConfigFile() etc, and this isn't illustrated at all in the examples\n> * Example workers don't interact with the pgstat subsystem\n>\n> Managing bgworker lifecycle is also quite difficult. The postmaster\n> doesn't offer any help and we don't expose much help from core. Any\n> extension that spawns workers needs to do its own handling of worker\n> startup registration in shmem, worker exit reaping, handling workers that\n> exit before registering, etc. This can be seen in the logical replication\n> code, which rolls its own management per\n> src/backend/replication/logical/launcher.c .\n>\n> PROPOSED CHANGES IN EXAMPLE BGWORKERS/CONTRIBS\n> -----\n>\n> So I'd like to make these changes to example bgworkers and to contrib\n> extensions:\n>\n> * Change example bgworkers in contrib to set up normal default signal\n> handlers, not define their own\n> * Add ConfigReloadPending and ProcessConfigFile() to all example bgworkers\n> * Show pgstat use in example bgworkers\n>\n> PROPOSED BGW SETUP AND MAINLOOP HELPERS\n> ----\n>\n> and I'm wondering if anyone thinks it's a good idea to add some bgworker\n> mainloop helper API, where one call is made at the start of the bgw, before\n> BackgroundWorkerInitializeConnection(), to:\n>\n> * set application_name\n> * set process title\n> * set up default signal handlers and unblock signals\n> * creates and assigns a BGWMemoryContext named after the bgw\n> * set state to idle in pgstat\n> * sets up MyProcPort (or teach InitPostgres to do so for a bgw)\n> * takes a function pointer for a before_shmem_exit cleanup handler\n> to encourage ext authors to use this approach\n>\n> then a mainloop helper that:\n>\n> * Checks that CurrentMemoryContext == BGWMemoryContext\n> * Runs CHECK_FOR_INTERRUPTS()\n> * Checks for postmaster death and exits\n> * Checks for and performs config file reload\n>\n>\n>\n> PROPOSED ERROR HANDLING HELPER\n> ----\n>\n> It'd also be beneficial to have a helper for bgw mainloops with error\n> recovery, generalizing and extracting the pattern I see in all these\n> routines:\n>\n> src/backend/postmaster/autovacuum.c=AutoVacLauncherMain\n> src/backend/postmaster/autovacuum.c=AutoVacWorkerMain\n> src/backend/postmaster/bgworker.c=StartBackgroundWorker\n> src/backend/postmaster/bgwriter.c=BackgroundWriterMain\n> src/backend/postmaster/checkpointer.c=CheckpointerMain\n> src/backend/postmaster/walwriter.c=WalWriterMain\n> src/backend/tcop/postgres.c=PostgresMain\n>\n> which all do their own error reset loops. There's way too much copy/paste\n> going on there IMO, even before we consider bgworkers, and it's nearly\n> impossible for anyone who isn't quite an experienced Pg developer to write\n> a bgw that can do anything with errors except promote ERROR to FATAL and\n> die.\n>\n> This would be modeled on PosgresMain(). The worker would only need to add\n> its own logic to the sigsetjmp() error jump path, not duplicate all the\n> core cleanup work.\n>\n> PROPOSED GENERALISED WORKER MANAGEMENT\n> ----\n>\n> Finally I'm wondering if there's any interest in generalizing the logical\n> rep worker management for other bgworkers. I've done a ton of work with\n> worker management and it's something I'm sure I could take on but I don't\n> want to write it without knowing there's some chance of acceptance.\n>\n> The general idea is to provide a way for bgworkers to start up managers\n> for pools / sets of workers. They launch them and have a function they can\n> call in their mainloop that watches their child worker states, invoking\n> callbacks when they fail to launch, launch successfully, exit cleanly after\n> finishing their work, or die with an error. Workers are tracked in a shmem\n> seg where the start of the seg must be a key struct (akin to how the hash\n> API works). We would provide calls to look up a worker shmem struct by key,\n> signal a worker by key, wait for a worker to exit (up to timeout), etc.\n> Like in the logical rep code, access to the worker registration shmem would\n> be controlled by LWLock. The extension code can put whatever it wants in\n> the worker shmem entries after the key, including various unions or\n> whatever - the worker management API won't care.\n>\n> This abstracts all the low level mess away from bgworker implementations\n> and lets them focus on writing the code they want to run.\n>\n> I'd probably suggest doing so by extracting the logical rep worker\n> management, and making the logical rep code use the generalized worker\n> management. So it'd be proven, and have in core users.\n>\n> PROPOSED XACT API WRAPPER\n> ----\n>\n> Additionally there are some more general postgres API patterns that the\n> team working on pglogical and BDR has landed up writing wrappers for or\n> compensating for. One of the most important is transaction management. In\n> many places in pglogical where we start lightweight transactions in\n> pglogical we use a wrapper that starts the txn if there isn't already one\n> open and remembers whether one was started. Then the end helper closes it\n> only if the start helper opened it. Finally, the memory context is always\n> reset to the memory context before txn start once the txn ends, instead of\n> being left at TopMemoryContext, since we've learned that that's an\n> extremely common source of bugs.\n>\n> I propose a wrapper for lightweight txn management, like the one we use in\n> many places in pglogical. This is not a copy of that code, it's just a\n> scratched out example of roughly how we do it:\n>\n> LocalTransactionState txn;\n> StartTransactionIfNotStarted(&txn, LXACT_WANT_SNAPSHOT);\n> ...\n> CommitTransactionCommandIfStarted(&txn);\n>\n> where\n>\n> static inline void\n> StartTransactionIfNotStarted(LocalTransactionState *txn, int flags)\n> {\n> txn->started = !TransactionInProgress();\n> txn->save_mctx = CurrentMemoryContext;\n> if (txn->started)\n> {\n> txn->pushed_snapshot = false;\n> StartTransactionCommand();\n> if (flags & LXACT_WANT_SNAPSHOT)\n> {\n> txn->pushed_snapshot = true;\n> PushActiveSnapshot(GetTransactionSnapshot());\n> }\n> }\n> }\n>\n> static inline void\n> CommitTransactionIfNotStarted(LocalTransactionState *txn)\n> {\n> if (txn->started)\n> {\n> Assert(TransactionInProgress());\n> Assert(CurrentMemoryContext == TopTransactionContext);\n> if (txn->pushed_snapshot)\n> PopActiveSnapshot();\n> CommitTransactionCommand();\n> }\n> else\n> {\n> /* Caller didn't change context between start and end */\n> Assert(CurrentMemoryContext == txn->save_mctx);\n> }\n> (void) MemoryContextSwitchTo(txn->save_mctx);\n> }\n>\n\nany from these proposal looks like good idea\n\nRegards\n\nPavel\n\n\n\n>\n> --\n> Craig Ringer http://www.2ndQuadrant.com/\n> 2ndQuadrant - PostgreSQL Solutions for the Enterprise\n>\n\nčt 10. 9. 2020 v 5:02 odesílatel Craig Ringer <craig@2ndquadrant.com> napsal:Hi allAs I've gained experience working on background workers, it's become increasingly clear that they're a bit too different to normal backends for many nontrivial uses.I thought I'd take a moment to note some of it here, along with some proposals for things we could potentially do to make it much easier to use bgworkers correctly especially when using them to run queries.This is NOT A PATCH SET. It's a set of discussion proposals and it's also intended as a bit of a helper for people just getting started on bgworkers. There are a lot of subtle differences in the runtime environment a basic bgworker provides vs the runtime environment extension authors will be used to when writing fmgr-callable C functions.(It looks like pg12 and pg13 have some improvements, so some of the issues I was going to mention with error cleanup paths and locking aren't relevant anymore.)DIFFERENCES WHEN CODING FOR BGWORKERS----Some of the most important differences vs normal backends that I've noticed are:* There's no supported way to recover from an error and continue execution. Each bgworker has to roll its own logic based on PostgresMain()'s sigsetjmp() handler and maintain it.* The bgworker infrastructure doesn't set up the the  application_name in PGPROC* Example bgworkers roll their own signal handlers rather than using die, procsignal_sigusr1_handler, and PostgresSigHupHandler. This makes them seem to work OK, but fail to respect CHECK_FOR_INTERRUPTS() and other expected behaviour when they call into the executor etc.* Each bgworker has to roll its own mainloop with ConfigReloadPending / ProcessConfigFile() etc, and this isn't illustrated at all in the examples* Example workers don't interact with the pgstat subsystemManaging bgworker lifecycle is also quite difficult. The postmaster doesn't offer any help and we don't expose much help from core. Any extension that spawns workers needs to do its own handling of worker startup registration in shmem, worker exit reaping, handling workers that exit before registering, etc. This can be seen in the logical replication code, which rolls its own management per src/backend/replication/logical/launcher.c .PROPOSED CHANGES IN EXAMPLE BGWORKERS/CONTRIBS-----So I'd like to make these changes to example bgworkers and to contrib extensions:* Change example bgworkers in contrib to set up normal default signal handlers, not define their own* Add ConfigReloadPending and ProcessConfigFile() to all example bgworkers* Show pgstat use in example bgworkersPROPOSED BGW SETUP AND MAINLOOP HELPERS ----and I'm wondering if anyone thinks it's a good idea to add some bgworker mainloop helper API, where one call is made at the start of the bgw, before BackgroundWorkerInitializeConnection(), to:* set application_name* set process title* set up default signal handlers and unblock signals* creates and assigns a BGWMemoryContext named after the bgw* set state to idle in pgstat* sets up MyProcPort (or teach InitPostgres to do so for a bgw)* takes a function pointer for a before_shmem_exit cleanup handler  to encourage ext authors to use this approachthen a mainloop helper that:* Checks that CurrentMemoryContext == BGWMemoryContext* Runs CHECK_FOR_INTERRUPTS() * Checks for postmaster death and exits* Checks for and performs config file reloadPROPOSED ERROR HANDLING HELPER----It'd also be beneficial to have a helper for bgw mainloops with error recovery, generalizing and extracting the pattern I see in all these routines:src/backend/postmaster/autovacuum.c=AutoVacLauncherMainsrc/backend/postmaster/autovacuum.c=AutoVacWorkerMainsrc/backend/postmaster/bgworker.c=StartBackgroundWorkersrc/backend/postmaster/bgwriter.c=BackgroundWriterMainsrc/backend/postmaster/checkpointer.c=CheckpointerMainsrc/backend/postmaster/walwriter.c=WalWriterMainsrc/backend/tcop/postgres.c=PostgresMainwhich all do their own error reset loops. There's way too much copy/paste going on there IMO, even before we consider bgworkers, and it's nearly impossible for anyone who isn't quite an experienced Pg developer to write a bgw that can do anything with errors except promote ERROR to FATAL and die.This would be modeled on PosgresMain(). The worker would only need to add its own logic to the sigsetjmp() error jump path, not duplicate all the core cleanup work.PROPOSED GENERALISED WORKER MANAGEMENT---- Finally I'm wondering if there's any interest in generalizing the logical rep worker management for other bgworkers. I've done a ton of work with worker management and it's something I'm sure I could take on but I don't want to write it without knowing there's some chance of acceptance.The general idea is to provide a way for bgworkers to start up managers for pools / sets of workers. They launch them and have a function they can call in their mainloop that watches their child worker states, invoking callbacks when they fail to launch, launch successfully, exit cleanly after finishing their work, or die with an error. Workers are tracked in a shmem seg where the start of the seg must be a key struct (akin to how the hash API works). We would provide calls to look up a worker shmem struct by key, signal a worker by key, wait for a worker to exit (up to timeout), etc. Like in the logical rep code, access to the worker registration shmem would be controlled by LWLock. The extension code can put whatever it wants in the worker shmem entries after the key, including various unions or whatever - the worker management API won't care.This abstracts all the low level mess away from bgworker implementations and lets them focus on writing the code they want to run.I'd probably suggest doing so by extracting the logical rep worker management, and making the logical rep code use the generalized worker management. So it'd be proven, and have in core users.PROPOSED XACT API WRAPPER----Additionally there are some more general postgres API patterns that the team working on pglogical and BDR has landed up writing wrappers for or compensating for. One of the most important is transaction management. In many places in pglogical where we start lightweight transactions in pglogical we use a wrapper that starts the txn if there isn't already one open and remembers whether one was started. Then the end helper closes it only if the start helper opened it. Finally, the memory context is always reset to the memory context before txn start once the txn ends, instead of being left at TopMemoryContext, since we've learned that that's an extremely common source of bugs.I propose a wrapper for lightweight txn management, like the one we use in many places in pglogical. This is not a copy of that code, it's just a scratched out example of roughly how we do it:LocalTransactionState txn;StartTransactionIfNotStarted(&txn, LXACT_WANT_SNAPSHOT);...CommitTransactionCommandIfStarted(&txn);wherestatic inline voidStartTransactionIfNotStarted(LocalTransactionState *txn, int flags){    txn->started = !TransactionInProgress();    txn->save_mctx = CurrentMemoryContext;    if (txn->started)    {        txn->pushed_snapshot = false;        StartTransactionCommand();        if (flags & LXACT_WANT_SNAPSHOT)        {            txn->pushed_snapshot = true;            PushActiveSnapshot(GetTransactionSnapshot());        }    }}static inline voidCommitTransactionIfNotStarted(LocalTransactionState *txn){    if (txn->started)    {        Assert(TransactionInProgress());        Assert(CurrentMemoryContext == TopTransactionContext);        if (txn->pushed_snapshot)            PopActiveSnapshot();        CommitTransactionCommand();    }    else    {        /* Caller didn't change context between start and end */        Assert(CurrentMemoryContext == txn->save_mctx);    }    (void) MemoryContextSwitchTo(txn->save_mctx);}any from these proposal looks like good ideaRegardsPavel --  Craig Ringer                   http://www.2ndQuadrant.com/ 2ndQuadrant - PostgreSQL Solutions for the Enterprise", "msg_date": "Thu, 10 Sep 2020 06:11:30 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Proposals for making it easier to write correct bgworkers" }, { "msg_contents": "On Thu, Sep 10, 2020 at 5:02 AM Craig Ringer <craig@2ndquadrant.com> wrote:\n\n> Hi all\n>\n> As I've gained experience working on background workers, it's become\n> increasingly clear that they're a bit too different to normal backends for\n> many nontrivial uses.\n>\n\n<snip> a lot of proposals I agree with.\n\n\n\nPROPOSED GENERALISED WORKER MANAGEMENT\n> ----\n>\n> Finally I'm wondering if there's any interest in generalizing the logical\n> rep worker management for other bgworkers. I've done a ton of work with\n> worker management and it's something I'm sure I could take on but I don't\n> want to write it without knowing there's some chance of acceptance.\n>\n> The general idea is to provide a way for bgworkers to start up managers\n> for pools / sets of workers. They launch them and have a function they can\n> call in their mainloop that watches their child worker states, invoking\n> callbacks when they fail to launch, launch successfully, exit cleanly after\n> finishing their work, or die with an error. Workers are tracked in a shmem\n> seg where the start of the seg must be a key struct (akin to how the hash\n> API works). We would provide calls to look up a worker shmem struct by key,\n> signal a worker by key, wait for a worker to exit (up to timeout), etc.\n> Like in the logical rep code, access to the worker registration shmem would\n> be controlled by LWLock. The extension code can put whatever it wants in\n> the worker shmem entries after the key, including various unions or\n> whatever - the worker management API won't care.\n>\n> This abstracts all the low level mess away from bgworker implementations\n> and lets them focus on writing the code they want to run.\n>\n> I'd probably suggest doing so by extracting the logical rep worker\n> management, and making the logical rep code use the generalized worker\n> management. So it'd be proven, and have in core users.\n>\n\nYes, there is definitely a lot of interest in this.\n\nIt would also be good to somehow generalize away the difference between\nstatic bgworkers and dynamic ones. That's something that really annoyed us\nwith the work on the \"online checksums\" patch, and I've also run into that\nissue in other cases. I think finding a way to launch a dynamic worker out\nof the postmaster would be a way to do that -- I haven't looked into the\ndetail, but if we're looking at generalizing the worker management this is\ndefinitely something we should include in the consideration.\n\nI haven't looked at the different places we could in theory extract the\nmanagement out of and reuse, but it makes sense that the logical\nreplication one would be the most appropriate since it's the newest one (vs\nautovacuum which is the other one that can at least do similar things). And\nyes, it definitely makes sense to have a generalized set of code for this,\nbecause it's certainly a fairly complicated pattern that we shouldn't be\nre-inventing over and over again with slightly different bugs.\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 Thu, Sep 10, 2020 at 5:02 AM Craig Ringer <craig@2ndquadrant.com> wrote:Hi allAs I've gained experience working on background workers, it's become increasingly clear that they're a bit too different to normal backends for many nontrivial uses.<snip> a lot of proposals I agree with.PROPOSED GENERALISED WORKER MANAGEMENT---- Finally I'm wondering if there's any interest in generalizing the logical rep worker management for other bgworkers. I've done a ton of work with worker management and it's something I'm sure I could take on but I don't want to write it without knowing there's some chance of acceptance.The general idea is to provide a way for bgworkers to start up managers for pools / sets of workers. They launch them and have a function they can call in their mainloop that watches their child worker states, invoking callbacks when they fail to launch, launch successfully, exit cleanly after finishing their work, or die with an error. Workers are tracked in a shmem seg where the start of the seg must be a key struct (akin to how the hash API works). We would provide calls to look up a worker shmem struct by key, signal a worker by key, wait for a worker to exit (up to timeout), etc. Like in the logical rep code, access to the worker registration shmem would be controlled by LWLock. The extension code can put whatever it wants in the worker shmem entries after the key, including various unions or whatever - the worker management API won't care.This abstracts all the low level mess away from bgworker implementations and lets them focus on writing the code they want to run.I'd probably suggest doing so by extracting the logical rep worker management, and making the logical rep code use the generalized worker management. So it'd be proven, and have in core users.Yes, there is definitely a lot of interest in this.It would also be good to somehow generalize away the difference between static bgworkers and dynamic ones. That's something that really annoyed us with the work on the \"online checksums\" patch, and I've also run into that issue in other cases. I think finding a way to launch a dynamic worker out of the postmaster would be a way to do that -- I haven't looked into the detail, but if we're looking at generalizing the worker management this is definitely something we should include in the consideration.I haven't looked at the different places we could in theory extract the management out of and reuse, but it makes sense that the logical replication one would be the most appropriate since it's the newest one (vs autovacuum which is the other one that can at least do similar things). And yes, it definitely makes sense to have a generalized set of code for this, because it's certainly a fairly complicated pattern that we shouldn't be re-inventing over and over again with slightly different bugs.--  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Thu, 10 Sep 2020 09:40:15 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: Proposals for making it easier to write correct bgworkers" }, { "msg_contents": "On Thu, Sep 10, 2020 at 11:02:07AM +0800, Craig Ringer wrote:\n> Hi all\n> \n> As I've gained experience working on background workers, it's become\n> increasingly clear that they're a bit too different to normal backends for many\n> nontrivial uses.\n> \n> I thought I'd take a moment to note some of it here, along with some proposals\n> for things we could potentially do to make it much easier to use bgworkers\n> correctly especially when using them to run queries.\n> \n> This is NOT A PATCH SET. It's a set of discussion proposals and it's also\n> intended as a bit of a helper for people just getting started on bgworkers.\n> There are a lot of subtle differences in the runtime environment a basic\n> bgworker provides vs the runtime environment extension authors will be used to\n> when writing fmgr-callable C functions.\n> \n> (It looks like pg12 and pg13 have some improvements, so some of the issues I\n> was going to mention with error cleanup paths and locking aren't relevant\n> anymore.)\n> \n> DIFFERENCES WHEN CODING FOR BGWORKERS\n\nCan we put this information somewhere in our docs or source code as a\nREADME?\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Fri, 18 Sep 2020 18:38:45 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Proposals for making it easier to write correct bgworkers" } ]
[ { "msg_contents": "I would like to propose new PostgreSQL Extension - PGSpiderExt.\n\n* What is PGSpiderExt\nThis extension makes it possible to treat multiple tables having the same schema as a single virtual table.\nWe call this table as a multi-tenant table.\nIf a foreign table has a key column identifying a table, you can realize it by using conventional declarative partitioning feature.\nBut, even if the foreign table does not have the key column, this extension can create such virtual table without changing table structure on foreign table.\n\n* Example of execution\nData of foreign table1:\n i | t\n----+---\n 10 | a\n 11 | b\n\nData of foreign table2:\n i | t\n----+---\n 20 | c\n 21 | d\n\n(Example1) Query and result for multi tenant table:\n't1' is a multi-tenant table having 'table1' and 'table2'.\n'node' is a key column of which values are 'node1' and 'node2' representing 'table1' and 'table2' respectively.\n\nSELECT * FROM t1;\n i | t | node\n----+---+-------\n 10 | a | node1\n 11 | b | node1\n 20 | c | node2\n 21 | d | node2\n\n(Example2) Query and result for multi tenant table:\nSELECT * FROM t1 WHERE node = 'node1';\n i | t | node\n----+---+-------\n 10 | a | node1\n 11 | b | node1\n\n\n* How to create a multi-tenant table\npgspider_ext is one of foreign data wrapper for creating intermediate tables between a partition parent table and foreign tables.\nFirstly, you create foreign tables using data source FDW such as postgres_fdw as usual.\nThen create a partition table using declarative partitioning feature.\nThis table has a partition key column of text type in addition to same columns as the foreign table, and is partitioned by List.\nAfter that, you create child tables of partition by using pgspider_ext.\nYou can define a value of partition key arbitrarily.\n\n* Internal mechanism of accessing multi-tenant table PostgreSQL core\nseparates a query into queries for intermediate tables by partitioning feature.\npgspider_ext receives and analyzes the query, then passes query information to data source FDW.\nMore specifically, pgspider_ext creates information so that data source FDW can create a plan.\nThen, creates a plan of intermediate table based on a plan created by data source FDW.\nAt that time, pgspider_ext does not pass query information about a partition key(like target list and WHERE condition) to data source FDW.\nWhen executing the query, data source FDW accesses to a foreign server and fetch a result set.\npgspider_ext receives and return it to PostgreSQL core by adding information of a partition key.\n\n* Example of usage\nCREATE EXTENSION pgspider_ext;\nCREATE EXTENSION postgres_fdw;\n\n-- Create a server for pgspider_ext.\nCREATE SERVER mtsrv FOREIGN DATA WRAPPER pgspider_ext;\n\n-- Define data sources. pgsrv1 has a table 't1_pg1' and pgsrv2 has a table 't1_pg2'.\n-- These tables have 2 columns: 'i' integer and 't' text.\nCREATE SERVER pgsrv1 FOREIGN DATA WRAPPER postgres_fdw OPTIONS(host\n'127.0.0.1', port '5433', dbname 'postgres'); CREATE SERVER pgsrv2\nFOREIGN DATA WRAPPER postgres_fdw OPTIONS(host '127.0.0.1', port\n'5434', dbname 'postgres');\n\nCREATE USER MAPPING FOR CURRENT_USER SERVER mtsrv; CREATE USER\nMAPPING FOR CURRENT_USER SERVER pgsrv1 OPTIONS(user 'user', password\n'pass'); CREATE USER MAPPING FOR CURRENT_USER SERVER pgsrv2\nOPTIONS(user 'user', password 'pass');\n\n-- Create foreign tables as usual using data source FDW.\nCREATE FOREIGN TABLE t1_pg1_ft (i int, t text) SERVER pgsrv1 OPTIONS\n(table_name 't1_pg1'); CREATE FOREIGN TABLE t1_pg2_ft (i int, t text)\nSERVER pgsrv2 OPTIONS (table_name 't1_pg2');\n\n-- Define a partition table and child tables using pgspider_ext.\n-- Partition key column is 'node' which does not exist on foreign table.\nCREATE TABLE t1(i int, t integer, node text) PARTITION BY LIST\n(node); CREATE FOREIGN TABLE t1_pg1_tenant PARTITION OF t1 FOR VALUES\nIN\n('node1') SERVER mtsrv OPTIONS (child_name 't1_pg1_ft'); CREATE\nFOREIGN TABLE t1_pg2_tenant PARTITION OF t1 FOR VALUES IN ('node2')\nSERVER mtsrv OPTIONS (child_name 't1_pg2_ft');\n\nThen, you can access t1 by SELECT query.\n\n*\nWe hope to be incorporated this extension into PostgreSQL as one of\ncontrib module, and would like to try to propose to Commit Fest.\nCould you kindly advise me and share your opinion?\n\nRegards,\nTaiga Katayama\n\n\n", "msg_date": "Thu, 10 Sep 2020 14:54:34 +0900", "msg_from": "Taiga KATAYAMA <taiga.katayama@toshiba.co.jp>", "msg_from_op": true, "msg_subject": "Proposal of new PostgreSQL Extension - PGSpiderExt" }, { "msg_contents": "> On 10 Sep 2020, at 07:54, Taiga KATAYAMA <taiga.katayama@toshiba.co.jp> wrote:\n\n> We hope to be incorporated this extension into PostgreSQL as one of\n> contrib module, and would like to try to propose to Commit Fest.\n> Could you kindly advise me and share your opinion?\n\nFWIW I would like to see fewer modules in contrib rather than gaining more, and\n(I can't stress this enough) that's not in any way a comment on the quality or\nthe usefulness of the extension in question here.\n\nThe outside-of-core ecosystem for postgres extensions has been discussed in\nvarious threads lately, and improving that seems a more sustainable solution\nthan bundling more. That's no doubt a lot easier said than done, but I think\nit's extremely important for the community.\n\ncheers ./daniel\n\n", "msg_date": "Thu, 10 Sep 2020 14:09:11 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Proposal of new PostgreSQL Extension - PGSpiderExt" }, { "msg_contents": "Thank you for your comment.\n\nPlease let me know if anyone has any other comments.\n\nRegards,\nTaiga Katayama\n\nOn 2020/09/10 21:09, Daniel Gustafsson wrote:\n>> On 10 Sep 2020, at 07:54, Taiga KATAYAMA <taiga.katayama@toshiba.co.jp> wrote:\n> \n>> We hope to be incorporated this extension into PostgreSQL as one of\n>> contrib module, and would like to try to propose to Commit Fest.\n>> Could you kindly advise me and share your opinion?\n> \n> FWIW I would like to see fewer modules in contrib rather than gaining more, and\n> (I can't stress this enough) that's not in any way a comment on the quality or\n> the usefulness of the extension in question here.\n> \n> The outside-of-core ecosystem for postgres extensions has been discussed in\n> various threads lately, and improving that seems a more sustainable solution\n> than bundling more. That's no doubt a lot easier said than done, but I think\n> it's extremely important for the community.\n> \n> cheers ./daniel\n> \n\n\n", "msg_date": "Wed, 16 Sep 2020 18:58:58 +0900", "msg_from": "Taiga KATAYAMA <taiga.katayama@toshiba.co.jp>", "msg_from_op": true, "msg_subject": "Re: Proposal of new PostgreSQL Extension - PGSpiderExt" }, { "msg_contents": "On Thu, Sep 10, 2020 at 02:09:11PM +0200, Daniel Gustafsson wrote:\n> FWIW I would like to see fewer modules in contrib rather than gaining more.\n\nAgreed here.\n--\nMichael", "msg_date": "Wed, 16 Sep 2020 22:01:29 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Proposal of new PostgreSQL Extension - PGSpiderExt" }, { "msg_contents": "\n\nOn 16.09.2020 16:01, Michael Paquier wrote:\n> On Thu, Sep 10, 2020 at 02:09:11PM +0200, Daniel Gustafsson wrote:\n>> FWIW I would like to see fewer modules in contrib rather than gaining more.\n> Agreed here.\n> --\n> Michael\n\nThe intention to limit the number of contrib modules seems to be obvious \nbecause\ncommunity will have to support all this modules.\n\nBut it will be great to have some have some common \"playground\" for all \nPostgres extension, so that everybody can easily\nlook for available extensions, check their status: which Postgres \nversion are supported, last update time, OS compatibility, author's \ncontacts...\nI think that it will be enough just to have common git repository for \nthem + may be some rules/tools which simplify search of extensions.\n\n From my point of view if will be very helpful if such \"PgExt Store\" \nwill be available.\nMay be such resources already exists, but I do not know about them.\nThere is the following page:\nhttps://www.postgresql.org/download/products/6-postgresql-extensions/\nbut there are just 13 extension listed here. And I failed to add my \nproduct in it.\n\nAs author of several Postgres extensions, I very interesting in having \nsome common\ndatabase of all available Postgres extension and be able to publish my� \nextensions there.\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Wed, 16 Sep 2020 17:17:25 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Proposal of new PostgreSQL Extension - PGSpiderExt" }, { "msg_contents": "> From my point of view if will be very helpful if such > \"PgExt Store\"\n> will be available.\n> May be such resources already exists, but I do not > know about them.\n\nhttps://pgxn.org/\n\n>  From my point of view if will be very helpful if such > \"PgExt Store\" > will be available.> May be such resources already exists, but I do not > know about them.https://pgxn.org/", "msg_date": "Wed, 16 Sep 2020 10:23:22 -0400", "msg_from": "Adam Brusselback <adambrusselback@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Proposal of new PostgreSQL Extension - PGSpiderExt" }, { "msg_contents": "On Wed, Sep 16, 2020 at 4:17 PM Konstantin Knizhnik\n<k.knizhnik@postgrespro.ru> wrote:\n>\n> On 16.09.2020 16:01, Michael Paquier wrote:\n> > On Thu, Sep 10, 2020 at 02:09:11PM +0200, Daniel Gustafsson wrote:\n> >> FWIW I would like to see fewer modules in contrib rather than gaining more.\n> > Agreed here.\n> > --\n> > Michael\n>\n> The intention to limit the number of contrib modules seems to be obvious\n> because\n> community will have to support all this modules.\n>\n> But it will be great to have some have some common \"playground\" for all\n> Postgres extension, so that everybody can easily\n> look for available extensions, check their status: which Postgres\n> version are supported, last update time, OS compatibility, author's\n> contacts...\n> I think that it will be enough just to have common git repository for\n> them + may be some rules/tools which simplify search of extensions.\n>\n> From my point of view if will be very helpful if such \"PgExt Store\"\n> will be available.\n> May be such resources already exists, but I do not know about them.\n> There is the following page:\n> https://www.postgresql.org/download/products/6-postgresql-extensions/\n> but there are just 13 extension listed here. And I failed to add my\n> product in it.\n>\n> As author of several Postgres extensions, I very interesting in having\n> some common\n> database of all available Postgres extension and be able to publish my\n> extensions there.\n\nThat's the goal of https://pgxn.org/. The major problem is that those\nextensions are usually not available on the various clouds, and/or\ndon't have the same trust level as for official contribs.\n\n\n", "msg_date": "Wed, 16 Sep 2020 16:28:06 +0200", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Proposal of new PostgreSQL Extension - PGSpiderExt" }, { "msg_contents": "On 16.09.2020 17:23, Adam Brusselback wrote:\n> >  From my point of view if will be very helpful if such > \"PgExt Store\"\n> > will be available.\n> > May be such resources already exists, but I do not > know about them.\n>\n> https://pgxn.org/\n\n\nThank you.\nShame on me, that I have forgot about it.\nActually I have even uploaded one of my extension (IMCS) to PGXN.\n\nMay be I am wrong, but it seems to me that not so much people know about \npgxn.org <https://pgxn.org/>\nBefore writing this mail I have tried to locate such resource in Google \nand didn't succeed.\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n\n\n\n\n\n\nOn 16.09.2020 17:23, Adam Brusselback\n wrote:\n\n\n\n\n>  From my point of view if will be very\n helpful if such > \"PgExt Store\" \n> will be available.\n> May be such resources already exists, but I\n do not > know about them.\n\n\nhttps://pgxn.org/\n\n\n\n Thank you.\n Shame on me, that I have forgot about it.\n Actually I have even uploaded one of my extension (IMCS) to PGXN.\n\n May be I am wrong, but it seems to me that not so much people know\n about pgxn.org\n Before writing this mail I have tried to locate such resource in\n Google and didn't succeed.\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Wed, 16 Sep 2020 18:08:35 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Proposal of new PostgreSQL Extension - PGSpiderExt" }, { "msg_contents": "st 16. 9. 2020 v 17:08 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 16.09.2020 17:23, Adam Brusselback wrote:\n>\n> > From my point of view if will be very helpful if such > \"PgExt Store\"\n> > will be available.\n> > May be such resources already exists, but I do not > know about them.\n>\n> https://pgxn.org/\n>\n>\n>\n> Thank you.\n> Shame on me, that I have forgot about it.\n> Actually I have even uploaded one of my extension (IMCS) to PGXN.\n>\n> May be I am wrong, but it seems to me that not so much people know about\n> pgxn.org\n> Before writing this mail I have tried to locate such resource in Google\n> and didn't succeed.\n>\n\nyes, It is not strongly joined with the Postgres community, and it doesn't\ndeploy binary (compiled) code if I know it. So for some people it is not\nusable.\n\nBut anytime this and similar repositories will have problems, because the\nextensions there are not reviewed, nobody did security check, nobody did QA.\n\nThis is useful for Postgres developers, for very advanced users, or for\nvery fearless users :).\n\nRegards\n\nPavel\n\n\n> --\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>\n\nst 16. 9. 2020 v 17:08 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n\n\nOn 16.09.2020 17:23, Adam Brusselback\n wrote:\n\n\n\n>  From my point of view if will be very\n helpful if such > \"PgExt Store\" \n> will be available.\n> May be such resources already exists, but I\n do not > know about them.\n\n\nhttps://pgxn.org/\n\n\n\n Thank you.\n Shame on me, that I have forgot about it.\n Actually I have even uploaded one of my extension (IMCS) to PGXN.\n\n May be I am wrong, but it seems to me that not so much people know\n about pgxn.org\n Before writing this mail I have tried to locate such resource in\n Google and didn't succeed.yes, It is not strongly joined with the Postgres community, and it doesn't deploy binary (compiled) code if I know it. So for some people it is not usable. But anytime this and similar repositories will have problems, because the extensions there are not reviewed, nobody did security check, nobody did QA.This is useful for Postgres developers, for very advanced users, or for very fearless users :). RegardsPavel\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Wed, 16 Sep 2020 17:40:30 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Proposal of new PostgreSQL Extension - PGSpiderExt" }, { "msg_contents": "On Wed, Sep 16, 2020 at 05:40:30PM +0200, Pavel Stehule wrote:\n> May be I am wrong, but it seems to me that not so much people know about\n> pgxn.org\n> Before writing this mail I have tried to locate such resource in Google and\n> didn't succeed.\n> \n> yes, It is not strongly joined with the Postgres community, and it doesn't\n> deploy binary (compiled) code if I know it. So for some people it is not\n> usable.\n> \n> But anytime this and similar repositories will have problems, because the\n> extensions there are not reviewed, nobody did security check, nobody did QA.\n> \n> This is useful for Postgres developers, for very advanced users, or for very\n> fearless users :).\n\nI think if PGXN had more must-have extensions, its popularity would\nincrease.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Fri, 18 Sep 2020 18:42:25 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Proposal of new PostgreSQL Extension - PGSpiderExt" }, { "msg_contents": "so 19. 9. 2020 v 0:42 odesílatel Bruce Momjian <bruce@momjian.us> napsal:\n\n> On Wed, Sep 16, 2020 at 05:40:30PM +0200, Pavel Stehule wrote:\n> > May be I am wrong, but it seems to me that not so much people know\n> about\n> > pgxn.org\n> > Before writing this mail I have tried to locate such resource in\n> Google and\n> > didn't succeed.\n> >\n> > yes, It is not strongly joined with the Postgres community, and it\n> doesn't\n> > deploy binary (compiled) code if I know it. So for some people it is not\n> > usable.\n> >\n> > But anytime this and similar repositories will have problems, because the\n> > extensions there are not reviewed, nobody did security check, nobody did\n> QA.\n> >\n> > This is useful for Postgres developers, for very advanced users, or for\n> very\n> > fearless users :).\n>\n> I think if PGXN had more must-have extensions, its popularity would\n> increase.\n>\n\nThere is nothing else. But it can be much more useful, if somebody does\nreview, or if allows compilation to target platform on server side, if has\nintegrated tests, ...\n\nRegards\n\nPavel\n\n\n\n> --\n> Bruce Momjian <bruce@momjian.us> https://momjian.us\n> EnterpriseDB https://enterprisedb.com\n>\n> The usefulness of a cup is in its emptiness, Bruce Lee\n>\n>\n\nso 19. 9. 2020 v 0:42 odesílatel Bruce Momjian <bruce@momjian.us> napsal:On Wed, Sep 16, 2020 at 05:40:30PM +0200, Pavel Stehule wrote:\n>     May be I am wrong, but it seems to me that not so much people know about\n>     pgxn.org\n>     Before writing this mail I have tried to locate such resource in Google and\n>     didn't succeed.\n> \n> yes, It is not strongly joined with the Postgres community, and it doesn't\n> deploy binary (compiled) code if I know it. So for some people it is not\n> usable.\n> \n> But anytime this and similar repositories will have problems, because the\n> extensions there are not reviewed, nobody did security check, nobody did QA.\n> \n> This is useful for Postgres developers, for very advanced users, or for very\n> fearless users :).\n\nI think if PGXN had more must-have extensions, its popularity would\nincrease.There is nothing else.  But it can be much more useful, if somebody does review, or if allows compilation to target platform on server side, if has integrated tests, ...RegardsPavel \n\n-- \n  Bruce Momjian  <bruce@momjian.us>        https://momjian.us\n  EnterpriseDB                             https://enterprisedb.com\n\n  The usefulness of a cup is in its emptiness, Bruce Lee", "msg_date": "Sat, 19 Sep 2020 06:14:58 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Proposal of new PostgreSQL Extension - PGSpiderExt" } ]
[ { "msg_contents": "Hi,\n\nThere is a recent build farm failure [1] in one of the test_decoding\ntests as pointed by Tom Lane [2]. The failure report is shown below:\n\n@@ -71,6 +71,8 @@\n data\n ------------------------------------------\n opening a streamed block for transaction\n+ closing a streamed block for transaction\n+ opening a streamed block for transaction\n streaming change for transaction\n streaming change for transaction\n streaming change for transaction\n@@ -83,7 +85,7 @@\n streaming change for transaction\n closing a streamed block for transaction\n committing streamed transaction\n-(13 rows)\n+(15 rows)\n\nHere, the symptoms are quite similar to what we have fixed in commit\n82a0ba7707 which is that an extra empty transaction is being decoded\nin the test. It can happen even if have instructed the test to 'skip\nempty xacts' for streaming transactions because the test_decoding\nplugin APIs (related to streaming changes for in-progress xacts) makes\nno effort to skip such empty xacts. It was kept intentionally like\nthat under the assumption that we would never try to stream empty\nxacts but on closer inspection of the code, it seems to me that\nassumption was not correct. Basically, we can pick to stream a\ntransaction that has change messages for\nREORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT and we don't send such\nmessages to downstream rather they are just to update the internal\nstate. So, in this particular failure, it is possible that autovacuum\ntransaction has got such a change message added by one of the other\ncommitted xact and on trying to stream it we get such additional\nmessages. The fix is to skip empty xacts when indicated by the user in\nstreaming APIs of test_decoding.\n\nThoughts?\n\n[1] - https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=skink&dt=2020-09-09+03%3A42%3A19\n[2] - https://www.postgresql.org/message-id/118303.1599691636%40sss.pgh.pa.us\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Thu, 10 Sep 2020 11:29:39 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": true, "msg_subject": "Bug in logical decoding of in-progress transactions" }, { "msg_contents": "On Thu, Sep 10, 2020 at 11:29 AM Amit Kapila <amit.kapila16@gmail.com>\nwrote:\n\n> Hi,\n>\n> There is a recent build farm failure [1] in one of the test_decoding\n> tests as pointed by Tom Lane [2]. The failure report is shown below:\n>\n> @@ -71,6 +71,8 @@\n> data\n> ------------------------------------------\n> opening a streamed block for transaction\n> + closing a streamed block for transaction\n> + opening a streamed block for transaction\n> streaming change for transaction\n> streaming change for transaction\n> streaming change for transaction\n> @@ -83,7 +85,7 @@\n> streaming change for transaction\n> closing a streamed block for transaction\n> committing streamed transaction\n> -(13 rows)\n> +(15 rows)\n>\n> Here, the symptoms are quite similar to what we have fixed in commit\n> 82a0ba7707 which is that an extra empty transaction is being decoded\n> in the test. It can happen even if have instructed the test to 'skip\n> empty xacts' for streaming transactions because the test_decoding\n> plugin APIs (related to streaming changes for in-progress xacts) makes\n> no effort to skip such empty xacts. It was kept intentionally like\n> that under the assumption that we would never try to stream empty\n> xacts but on closer inspection of the code, it seems to me that\n> assumption was not correct. Basically, we can pick to stream a\n> transaction that has change messages for\n> REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT and we don't send such\n> messages to downstream rather they are just to update the internal\n> state. So, in this particular failure, it is possible that autovacuum\n> transaction has got such a change message added by one of the other\n> committed xact and on trying to stream it we get such additional\n> messages. The fix is to skip empty xacts when indicated by the user in\n> streaming APIs of test_decoding.\n>\n> Thoughts?\n>\n\nYeah, that's an issue.\n\n\n>\n> [1] -\n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=skink&dt=2020-09-09+03%3A42%3A19\n> [2] -\n> https://www.postgresql.org/message-id/118303.1599691636%40sss.pgh.pa.us\n>\n>\nI have written a test case to reproduce the same. I have also prepared a\npatch to skip the empty transaction. And after that, the issue has been\nfixed. But the extra side effect will be that it would skip any empty\nstream even if the transaction is not empty. As such I don't see any\nproblem with that but this is not what the user has asked for.\n\nlogical_decoding_work_mem=64kB\nSET synchronous_commit = on;\nSELECT 'init' FROM pg_create_logical_replication_slot('regression_slot',\n'test_decoding');\n\nCREATE TABLE stream_test(data text);\n\n-- consume DDL\nSELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL,\n'include-xids', '0', 'skip-empty-xacts', '1');\nCREATE OR REPLACE FUNCTION large_val() RETURNS TEXT LANGUAGE SQL AS 'select\narray_agg(md5(g::text))::text from generate_series(1, 80000) g';\n\n--session1\nBEGIN;\nCREATE TABLE stream_test1(data text);\n\n--session2\nBEGIN;\nCREATE TABLE stream_test2(data text);\nCOMMIT;\n\n--session3\nBEGIN;\nINSERT INTO stream_test SELECT large_val();\nSELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL,\n'include-xids', '1', 'skip-empty-xacts', '1', 'stream-changes', '1');\n\n data\n--------------------------------------------------\n opening a streamed block for transaction TXN 508\n closing a streamed block for transaction TXN 508\n opening a streamed block for transaction TXN 510\n streaming change for TXN 510\n closing a streamed block for transaction TXN 510\n(5 rows)\n\n\nAfter patch\n data\n--------------------------------------------------\n opening a streamed block for transaction TXN 510\n streaming change for TXN 510\n closing a streamed block for transaction TXN 510\n\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Thu, 10 Sep 2020 11:42:22 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Bug in logical decoding of in-progress transactions" }, { "msg_contents": "On Thu, Sep 10, 2020 at 11:42 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Thu, Sep 10, 2020 at 11:29 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>>\n>> Hi,\n>>\n>> There is a recent build farm failure [1] in one of the test_decoding\n>> tests as pointed by Tom Lane [2]. The failure report is shown below:\n>>\n>> @@ -71,6 +71,8 @@\n>> data\n>> ------------------------------------------\n>> opening a streamed block for transaction\n>> + closing a streamed block for transaction\n>> + opening a streamed block for transaction\n>> streaming change for transaction\n>> streaming change for transaction\n>> streaming change for transaction\n>> @@ -83,7 +85,7 @@\n>> streaming change for transaction\n>> closing a streamed block for transaction\n>> committing streamed transaction\n>> -(13 rows)\n>> +(15 rows)\n>>\n>> Here, the symptoms are quite similar to what we have fixed in commit\n>> 82a0ba7707 which is that an extra empty transaction is being decoded\n>> in the test. It can happen even if have instructed the test to 'skip\n>> empty xacts' for streaming transactions because the test_decoding\n>> plugin APIs (related to streaming changes for in-progress xacts) makes\n>> no effort to skip such empty xacts. It was kept intentionally like\n>> that under the assumption that we would never try to stream empty\n>> xacts but on closer inspection of the code, it seems to me that\n>> assumption was not correct. Basically, we can pick to stream a\n>> transaction that has change messages for\n>> REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT and we don't send such\n>> messages to downstream rather they are just to update the internal\n>> state. So, in this particular failure, it is possible that autovacuum\n>> transaction has got such a change message added by one of the other\n>> committed xact and on trying to stream it we get such additional\n>> messages. The fix is to skip empty xacts when indicated by the user in\n>> streaming APIs of test_decoding.\n>>\n>> Thoughts?\n>\n>\n> Yeah, that's an issue.\n>\n>>\n>>\n>> [1] - https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=skink&dt=2020-09-09+03%3A42%3A19\n>> [2] - https://www.postgresql.org/message-id/118303.1599691636%40sss.pgh.pa.us\n>>\n>\n> I have written a test case to reproduce the same. I have also prepared a patch to skip the empty transaction. And after that, the issue has been fixed. But the extra side effect will be that it would skip any empty stream even if the transaction is not empty. As such I don't see any problem with that but this is not what the user has asked for.\n>\n\nIsn't that true for non-streaming xacts as well? Basically\nskip-empty-xacts option indicates that if there is no change for\n'tuple' or 'message', we skip it.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Thu, 10 Sep 2020 11:47:30 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Bug in logical decoding of in-progress transactions" }, { "msg_contents": "On Thu, Sep 10, 2020 at 11:47 AM Amit Kapila <amit.kapila16@gmail.com>\nwrote:\n\n> On Thu, Sep 10, 2020 at 11:42 AM Dilip Kumar <dilipbalaut@gmail.com>\n> wrote:\n> >\n> > On Thu, Sep 10, 2020 at 11:29 AM Amit Kapila <amit.kapila16@gmail.com>\n> wrote:\n> >>\n> >> Hi,\n> >>\n> >> There is a recent build farm failure [1] in one of the test_decoding\n> >> tests as pointed by Tom Lane [2]. The failure report is shown below:\n> >>\n> >> @@ -71,6 +71,8 @@\n> >> data\n> >> ------------------------------------------\n> >> opening a streamed block for transaction\n> >> + closing a streamed block for transaction\n> >> + opening a streamed block for transaction\n> >> streaming change for transaction\n> >> streaming change for transaction\n> >> streaming change for transaction\n> >> @@ -83,7 +85,7 @@\n> >> streaming change for transaction\n> >> closing a streamed block for transaction\n> >> committing streamed transaction\n> >> -(13 rows)\n> >> +(15 rows)\n> >>\n> >> Here, the symptoms are quite similar to what we have fixed in commit\n> >> 82a0ba7707 which is that an extra empty transaction is being decoded\n> >> in the test. It can happen even if have instructed the test to 'skip\n> >> empty xacts' for streaming transactions because the test_decoding\n> >> plugin APIs (related to streaming changes for in-progress xacts) makes\n> >> no effort to skip such empty xacts. It was kept intentionally like\n> >> that under the assumption that we would never try to stream empty\n> >> xacts but on closer inspection of the code, it seems to me that\n> >> assumption was not correct. Basically, we can pick to stream a\n> >> transaction that has change messages for\n> >> REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT and we don't send such\n> >> messages to downstream rather they are just to update the internal\n> >> state. So, in this particular failure, it is possible that autovacuum\n> >> transaction has got such a change message added by one of the other\n> >> committed xact and on trying to stream it we get such additional\n> >> messages. The fix is to skip empty xacts when indicated by the user in\n> >> streaming APIs of test_decoding.\n> >>\n> >> Thoughts?\n> >\n> >\n> > Yeah, that's an issue.\n> >\n> >>\n> >>\n> >> [1] -\n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=skink&dt=2020-09-09+03%3A42%3A19\n> >> [2] -\n> https://www.postgresql.org/message-id/118303.1599691636%40sss.pgh.pa.us\n> >>\n> >\n> > I have written a test case to reproduce the same. I have also prepared\n> a patch to skip the empty transaction. And after that, the issue has been\n> fixed. But the extra side effect will be that it would skip any empty\n> stream even if the transaction is not empty. As such I don't see any\n> problem with that but this is not what the user has asked for.\n> >\n>\n> Isn't that true for non-streaming xacts as well? Basically\n> skip-empty-xacts option indicates that if there is no change for\n> 'tuple' or 'message', we skip it.\n>\n\nYeah, that's right.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\nOn Thu, Sep 10, 2020 at 11:47 AM Amit Kapila <amit.kapila16@gmail.com> wrote:On Thu, Sep 10, 2020 at 11:42 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Thu, Sep 10, 2020 at 11:29 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>>\n>> Hi,\n>>\n>> There is a recent build farm failure [1] in one of the test_decoding\n>> tests as pointed by Tom Lane [2]. The failure report is shown below:\n>>\n>> @@ -71,6 +71,8 @@\n>>                     data\n>>  ------------------------------------------\n>>   opening a streamed block for transaction\n>> + closing a streamed block for transaction\n>> + opening a streamed block for transaction\n>>   streaming change for transaction\n>>   streaming change for transaction\n>>   streaming change for transaction\n>> @@ -83,7 +85,7 @@\n>>   streaming change for transaction\n>>   closing a streamed block for transaction\n>>   committing streamed transaction\n>> -(13 rows)\n>> +(15 rows)\n>>\n>> Here, the symptoms are quite similar to what we have fixed in commit\n>> 82a0ba7707 which is that an extra empty transaction is being decoded\n>> in the test. It can happen even if have instructed the test to 'skip\n>> empty xacts' for streaming transactions because the test_decoding\n>> plugin APIs (related to streaming changes for in-progress xacts) makes\n>> no effort to skip such empty xacts. It was kept intentionally like\n>> that under the assumption that we would never try to stream empty\n>> xacts but on closer inspection of the code, it seems to me that\n>> assumption was not correct. Basically, we can pick to stream a\n>> transaction that has change messages for\n>> REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT and we don't send such\n>> messages to downstream rather they are just to update the internal\n>> state. So, in this particular failure, it is possible that autovacuum\n>> transaction has got such a change message added by one of the other\n>> committed xact and on trying to stream it we get such additional\n>> messages. The fix is to skip empty xacts when indicated by the user in\n>> streaming APIs of test_decoding.\n>>\n>> Thoughts?\n>\n>\n> Yeah, that's an issue.\n>\n>>\n>>\n>> [1] - https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=skink&dt=2020-09-09+03%3A42%3A19\n>> [2] - https://www.postgresql.org/message-id/118303.1599691636%40sss.pgh.pa.us\n>>\n>\n> I have written a test case to reproduce the same.  I have also prepared a patch to skip the empty transaction.  And after that, the issue has been fixed.  But the extra side effect will be that it would skip any empty stream even if the transaction is not empty.  As such I don't see any problem with that but this is not what the user has asked for.\n>\n\nIsn't that true for non-streaming xacts as well? Basically\nskip-empty-xacts option indicates that if there is no change for\n'tuple' or 'message', we skip it.Yeah, that's right. -- Regards,Dilip KumarEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Thu, 10 Sep 2020 11:53:19 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Bug in logical decoding of in-progress transactions" }, { "msg_contents": "On Thu, Sep 10, 2020 at 11:53 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n\n> On Thu, Sep 10, 2020 at 11:47 AM Amit Kapila <amit.kapila16@gmail.com>\n> wrote:\n>\n>> On Thu, Sep 10, 2020 at 11:42 AM Dilip Kumar <dilipbalaut@gmail.com>\n>> wrote:\n>> >\n>> > On Thu, Sep 10, 2020 at 11:29 AM Amit Kapila <amit.kapila16@gmail.com>\n>> wrote:\n>> >>\n>> >> Hi,\n>> >>\n>> >> There is a recent build farm failure [1] in one of the test_decoding\n>> >> tests as pointed by Tom Lane [2]. The failure report is shown below:\n>> >>\n>> >> @@ -71,6 +71,8 @@\n>> >> data\n>> >> ------------------------------------------\n>> >> opening a streamed block for transaction\n>> >> + closing a streamed block for transaction\n>> >> + opening a streamed block for transaction\n>> >> streaming change for transaction\n>> >> streaming change for transaction\n>> >> streaming change for transaction\n>> >> @@ -83,7 +85,7 @@\n>> >> streaming change for transaction\n>> >> closing a streamed block for transaction\n>> >> committing streamed transaction\n>> >> -(13 rows)\n>> >> +(15 rows)\n>> >>\n>> >> Here, the symptoms are quite similar to what we have fixed in commit\n>> >> 82a0ba7707 which is that an extra empty transaction is being decoded\n>> >> in the test. It can happen even if have instructed the test to 'skip\n>> >> empty xacts' for streaming transactions because the test_decoding\n>> >> plugin APIs (related to streaming changes for in-progress xacts) makes\n>> >> no effort to skip such empty xacts. It was kept intentionally like\n>> >> that under the assumption that we would never try to stream empty\n>> >> xacts but on closer inspection of the code, it seems to me that\n>> >> assumption was not correct. Basically, we can pick to stream a\n>> >> transaction that has change messages for\n>> >> REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT and we don't send such\n>> >> messages to downstream rather they are just to update the internal\n>> >> state. So, in this particular failure, it is possible that autovacuum\n>> >> transaction has got such a change message added by one of the other\n>> >> committed xact and on trying to stream it we get such additional\n>> >> messages. The fix is to skip empty xacts when indicated by the user in\n>> >> streaming APIs of test_decoding.\n>> >>\n>> >> Thoughts?\n>> >\n>> >\n>> > Yeah, that's an issue.\n>> >\n>> >>\n>> >>\n>> >> [1] -\n>> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=skink&dt=2020-09-09+03%3A42%3A19\n>> >> [2] -\n>> https://www.postgresql.org/message-id/118303.1599691636%40sss.pgh.pa.us\n>> >>\n>> >\n>> > I have written a test case to reproduce the same. I have also prepared\n>> a patch to skip the empty transaction. And after that, the issue has been\n>> fixed. But the extra side effect will be that it would skip any empty\n>> stream even if the transaction is not empty. As such I don't see any\n>> problem with that but this is not what the user has asked for.\n>> >\n>>\n>> Isn't that true for non-streaming xacts as well? Basically\n>> skip-empty-xacts option indicates that if there is no change for\n>> 'tuple' or 'message', we skip it.\n>>\n>\n> Yeah, that's right.\n>\n\nI have removed some comments which are not valid after this patch.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Thu, 10 Sep 2020 12:00:00 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Bug in logical decoding of in-progress transactions" }, { "msg_contents": "On Thu, Sep 10, 2020 at 12:00 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Thu, Sep 10, 2020 at 11:53 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>>\n>>> >\n>>> > I have written a test case to reproduce the same.\n>\n\nCan we write an isolation test for this scenario? See some similar\ntests in contrib/test_decoding/specs. If that is possible then we can\nprobably remove the test which failed and instead write an isolation\ntest involving three transactions as shown by you. Also, please\nprepare two separate patches (one for test and other for code) if you\nare able to convert existing test to an isolation test as that will\nmake it easier to test the fix.\n\n>\n> I have removed some comments which are not valid after this patch.\n>\n\nFew comments:\n=============\n1. We need to set xact_wrote_changes in pg_decode_stream_truncate() as\nwell along with the APIs in which you have set it.\n2.\n+static void\n+pg_output_stream_start(LogicalDecodingContext *ctx, TestDecodingData\n*data, ReorderBufferTXN *txn, bool last_write)\n+{\n OutputPluginPrepareWrite(ctx, true);\n if (data->include_xids)\n appendStringInfo(ctx->out, \"opening a streamed block for transaction\nTXN %u\", txn->xid);\n@@ -601,16 +610,15 @@ pg_decode_stream_start(LogicalDecodingContext *ctx,\n OutputPluginWrite(ctx, true);\n\nIn this API, we need to use 'last_write' in OutputPluginPrepareWrite()\nand OutputPluginWrite().\n\nThe attached patch fixes both these comments.\n\n-- \nWith Regards,\nAmit Kapila.", "msg_date": "Thu, 10 Sep 2020 14:47:44 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Bug in logical decoding of in-progress transactions" }, { "msg_contents": "On Thu, Sep 10, 2020 at 2:48 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> On Thu, Sep 10, 2020 at 12:00 PM Dilip Kumar <dilipbalaut@gmail.com>\n> wrote:\n> >\n> > On Thu, Sep 10, 2020 at 11:53 AM Dilip Kumar <dilipbalaut@gmail.com>\n> wrote:\n> >>\n> >>> >\n> >>> > I have written a test case to reproduce the same.\n> >\n>\n> Can we write an isolation test for this scenario? See some similar\n> tests in contrib/test_decoding/specs. If that is possible then we can\n> probably remove the test which failed and instead write an isolation\n> test involving three transactions as shown by you. Also, please\n> prepare two separate patches (one for test and other for code) if you\n> are able to convert existing test to an isolation test as that will\n> make it easier to test the fix.\n>\n\nI have written a test in isolation test. IMHO, we should not try to merge\nstream.sql to this isolation test mainly for two reasons a) this isolation\ntest is very specific that while we are trying to stream we must have the\nincomplete changes so if we try to put more operation like\nmessage/truncate/abort then it will become unpredictable. Currently, I\nhave kept it with just one big tuple so it is a guarantee that whenever the\nthe logical_decoding_work_mem exceed then it will have the partial\nchanges. b) we can add another operation in the transaction and cover the\nstream changes but then those are not very specific to the isolation test.\nSo I feel it is better to put only the specific scenario in the isolation\ntest.\n\n\n\n>\n> >\n> > I have removed some comments which are not valid after this patch.\n> >\n>\n> Few comments:\n> =============\n> 1. We need to set xact_wrote_changes in pg_decode_stream_truncate() as\n> well along with the APIs in which you have set it.\n> 2.\n> +static void\n> +pg_output_stream_start(LogicalDecodingContext *ctx, TestDecodingData\n> *data, ReorderBufferTXN *txn, bool last_write)\n> +{\n> OutputPluginPrepareWrite(ctx, true);\n> if (data->include_xids)\n> appendStringInfo(ctx->out, \"opening a streamed block for transaction\n> TXN %u\", txn->xid);\n> @@ -601,16 +610,15 @@ pg_decode_stream_start(LogicalDecodingContext *ctx,\n> OutputPluginWrite(ctx, true);\n>\n> In this API, we need to use 'last_write' in OutputPluginPrepareWrite()\n> and OutputPluginWrite().\n>\n> The attached patch fixes both these comments.\n>\n\nOkay, there is some change in stream.out so I have included that in the\nfirst patch.\n\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Thu, 10 Sep 2020 16:01:07 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Bug in logical decoding of in-progress transactions" }, { "msg_contents": "On Thu, Sep 10, 2020 at 4:01 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n>\n> Okay, there is some change in stream.out so I have included that in the first patch.\n>\n\nPushed after minor changes in comments.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Fri, 11 Sep 2020 14:33:20 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Bug in logical decoding of in-progress transactions" } ]
[ { "msg_contents": "Answers inline below, sorry for the formatting-- am still trying to get corporate email to work nicely with this mailing list, thanks.\r\n\r\nOn 9/9/20, 9:22 PM, \"Justin Pryzby\" <pryzby@telsasoft.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, Sep 08, 2020 at 06:25:03PM +0000, Jameson, Hunter 'James' wrote:\r\n > Hi, I ran across a small (but annoying) bug in initializing parallel BTree scans, which causes the parallel-scan state machine to get confused. The fix is one line; the description is a bit longer—\r\n\r\n What postgres version was this ?\r\n\r\nWe have observed this bug on PostgreSQL versions 11.x and 10.x. I don't believe it occurs in PostgreSQL versions 9.x, because 9.x does not have parallel BTree scan.\r\n\r\n > Before, function _bt_first() would exit immediately if the specified scan keys could never be satisfied--without notifying other parallel workers, if any, that the scan key was done. This moved that particular worker to a scan key beyond what was in the shared parallel-query state, so that it would later try to read in \"InvalidBlockNumber\", without recognizing it as a special sentinel value.\r\n >\r\n > The basic bug is that the BTree parallel query state machine assumes that a worker process is working on a key <= the global key--a worker process can be behind (i.e., hasn't finished its work on a previous key), but never ahead. By allowing the first worker to move on to the next scan key, in this one case, without notifying other workers, the global key ends up < the first worker's local key.\r\n >\r\n > Symptoms of the bug are: on R/O, we get an error saying we can't extend the index relation, while on an R/W we just extend the index relation by 1 block.\r\n\r\n What's the exact error ? Are you able to provide a backtrace ?\r\n\r\nI am not able to provide a full backtrace, unfortunately, but the relevant part appears to be:\r\n\r\n ReadBuffer (... blockNum=blockNum@entry=4294967295)\r\n _bt_getbuf (... blkno=4294967295 ...)\r\n _bt_readnextpage (... blkno=4294967295 ... )\r\n _bt_steppage (...)\r\n _bt_next (...)\r\n btgettuple (...)\r\n index_getnext_tid (...)\r\n index_getnext (...)\r\n IndexNext (...) \r\n\r\nNotice that _bt_steppage() is passing InvalidBlockNumber to ReadBuffer(). That is the bug.\r\n\r\n > To reproduce, you need a query that:\r\n >\r\n > 1. Executes parallel BTree index scan;\r\n > 2. Has an IN-list of size > 1;\r\n\r\n Do you mean you have an index on col1 and a query condition like: col1 IN (a,b,c...) ?\r\n\r\nSomething like that, yes,\r\n\r\n > 3. Has an additional index filter that makes it impossible to satisfy the\r\n > first IN-list condition.\r\n\r\n .. AND col1::text||'foo' = '';\r\n I think you mean that the \"impossible\" condition makes it so that a btree\r\n worker exits early.\r\n\r\nSpecifically, on that worker, _bt_first() sees !so->qual_ok and just returns \"false\". That is the bug. The fix is that the worker must also call _bt_parallel_done(scan), as is done everywhere else in _bt_first() where it returns \"false\".\r\n\r\n > (We encountered such a query, and therefore the bug, on a production instance.)\r\n\r\n Could you send the \"shape\" of the query or its plan, obfuscated and redacted as\r\n need be ?\r\n\r\nPlan is something like:\r\n\r\nFinalize GroupAggregate ... (... loops=1)\r\n Group Key: (...)\r\n -> Gather Merge ... (... loops=1)\r\n Workers Planned: 2\r\n Workers Launched: 2\r\n -> Partial GroupAggregate ... (... loops=3)\r\n Group Key: (...)\r\n -> Sort ... (... loops=3)\r\n Sort Key: (...)\r\n Sort Method: quicksort ...\r\n -> Nested Loop ... (... loops=3)\r\n -> Parallel Index Scan using ... (... loops=3)\r\n Index Cond: (((f ->> 't') >= ... ) AND ((f ->> 't') < ...) AND (((f -> 'c') ->> 't') = ANY (...)) AND (((f-> 'c') ->> 't') = ...))\r\n Filter: (CASE WHEN ... END IS NOT NULL)\r\n Rows Removed by Filter: ...\r\n -> Index Only Scan using ... (... rows=1 loops=...)\r\n Index Cond: (a = b)\r\n Heap Fetches: ...\r\n\r\n --\r\n Justin\r\n\r\nJames\r\n--\r\nJames Hunter, Amazon Web Services (AWS)\r\n\r\n\r\n\r\n", "msg_date": "Thu, 10 Sep 2020 18:02:15 +0000", "msg_from": "\"Jameson, Hunter 'James'\" <hunjmes@amazon.com>", "msg_from_op": true, "msg_subject": "Re: Fix for parallel BTree initialization bug" } ]
[ { "msg_contents": "Answers inline below:\r\n\r\nOn 9/10/20, 4:58 AM, \"Amit Kapila\" <amit.kapila16@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, Sep 8, 2020 at 11:55 PM Jameson, Hunter 'James'\r\n <hunjmes@amazon.com> wrote:\r\n >\r\n > Hi, I ran across a small (but annoying) bug in initializing parallel BTree scans, which causes the parallel-scan state machine to get confused. The fix is one line; the description is a bit longer—\r\n >\r\n >\r\n >\r\n > Before, function _bt_first() would exit immediately if the specified scan keys could never be satisfied--without notifying other parallel workers, if any, that the scan key was done.\r\n >\r\n\r\n The first question that comes to mind is how is it possible that for\r\n one of the workers specified scan keys is not satisfied while for\r\n others it is satisfied? I think it is possible when other workers are\r\n still working on the previous scan key and this worker has moved to\r\n the next scan key. If not, then what is the other case?\r\n\r\nI think that's right. If I remember correctly, the first to move to the next IN-list condition exits early and *locally* moves on to the next-next IN-list condition, but doesn't properly advance the global scan key. At that point, \"By allowing the first worker to move on to the next scan key, in this one case, without notifying other workers, the global key ends up < the first worker's local key.\" So the first worker now has a local scan key > the global scan key, because it didn't call _bt_parallel_done().\r\n\r\n > This moved that particular worker to a scan key beyond what was in the shared parallel-query state, so that it would later try to read in \"InvalidBlockNumber\", without recognizing it as a special sentinel value.\r\n >\r\n\r\n Now, if it happens as I mentioned then the other workers should not\r\n try to advance their scan because their local scan key will be lesser\r\n than shared key. Basically, they should return from the below\r\n condition:\r\n _bt_parallel_seize()\r\n {\r\n ..\r\n if (so->arrayKeyCount < btscan->btps_arrayKeyCount)\r\n {\r\n /* Parallel scan has already advanced to a new set of scankeys. */\r\n status = false;\r\n }\r\n ..\r\n }\r\n\r\n After this, those workers will also update their scan key and move\r\n forward from there. So, I am not seeing how this could create a\r\n problem.\r\n\r\nI think, if I understand my notes on the bug, that the problem is with the first worker, not the other workers. So it doesn't matter if the other workers aren't confused, because the first worker confuses itself. The first worker has moved on, without telling anyone else, basically.\r\n\r\n --\r\n With Regards,\r\n Amit Kapila.\r\n\r\nThanks,\r\nJames\r\n--\r\nJames Hunter, Amazon Web Services (AWS)\r\n\r\n\r\n", "msg_date": "Thu, 10 Sep 2020 18:09:19 +0000", "msg_from": "\"Jameson, Hunter 'James'\" <hunjmes@amazon.com>", "msg_from_op": true, "msg_subject": "Re: Fix for parallel BTree initialization bug" } ]
[ { "msg_contents": "Disclaimer: I'm not a native speaker, so not sure those are actually\nincorrect, and can't offer non-trivial suggestions.\n\nGeneral ones:\n. \"boolean\" vs \"Boolean\" --- usage seems to be inconsistent, even in the\nsame context.\n\n. Transaction isolation levels are sometimes called \"transaction isolation\nmodes\", is that correct?\n\n. In https://www.postgresql.org/docs/current/tableam.html, links to source\ncode\n are also hyperlinks into git, like (from SGML source):\n\n For details, please refer to the <ulink\nurl=\"https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/include/access/tableam.h;hb=HEAD\">\n <filename>src/include/access/tableam.h</filename></ulink> file.\n\n Perhaps, other similar links in documentation should also be made into\n hyperlinks?\n\n--------------------------------------------------------------------------------\nSpecific ones:\n\n--\nhttps://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS\n\n4.1.2.4 Dollar-quoted String Constants\n\nWhile the standard syntax for specifying string constants is usually\nconvenient, it can be difficult to understand when the desired string\ncontains\nmany single quotes or backslashes, since each of those must be doubled.\n -- Not so for backslashes (perhaps, this sentence is from\n pre-standard_conforming_strings ages).\n\n----- <in the same section> ------\n\nNotice that inside the dollar-quoted string, single quotes can be used\nwithout\nneeding to be escaped. Indeed, no characters inside a dollar-quoted string\nare\never escaped: the string content is always written literally. Backslashes\nare\nnot special, and neither are dollar signs, unless they are part of a\nsequence\nmatching the opening tag.\n -- Backslashes, again. Though here in may be justified, not sure.\n\n----- <in the same section> ------\n\n$function$\nBEGIN\n RETURN ($1 ~ $q$[\\t\\r\\n\\v\\\\]$q$);\nEND;\n$function$\n -- While it's understandable what the example is trying to demonstrate,\n single-quoted string would work here, too (so, no actual advantage, in\n this case).\n\n----- <in the same section> ------\n\nWith single-quote syntax, each backslash in the above example would have to\nbe\nwritten as four backslashes, which would be reduced to two backslashes in\nparsing the original string constant, and then to one when the inner string\nconstant is re-parsed during function execution.\n -- Nothing needs to be changed about backslashes, yet again.\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/ddl-basics.html\n5.1. Table Basics\n\nA table in a relational database is much like a table on paper: It consists\nof\nrows and columns.\n -- Why \"I\" in It after \":\" is capitalized?\n\n----- <in the same section> ------\nSome of the frequently used data types are integer for whole numbers,\nnumeric\nfor possibly fractional numbers, text for character strings, date for dates,\ntime for time-of-day values, and timestamp for values containing both date\nand\ntime.\n -- Perhaps, add (or replace with) timestamptz for storing moments in time\n(or\n something like that)?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-EXCLUSION\n\n5.4.6. Exclusion Constraints\n\nExclusion constraints ensure that if any two rows are compared on the\nspecified\ncolumns or expressions using the specified operators, at least one of these\noperator comparisons will return false or null. The syntax is:\n\nCREATE TABLE circles (\n c circle,\n EXCLUDE USING gist (c WITH &&)\n);\n -- Not only the definition is hard to grasp, but the example doesn't\nclarify\n a lot, as it's not explained what it actually achieves (especially\ngiven\n geometric data types and operators are described several chapters\nlater).\n\n--------------------------------------------------------------------------------\nhttps://www.postgresql.org/docs/current/ddl-alter.html#DDL-ALTER-REMOVING-A-CONSTRAINT\n\n5.6.4. Removing a Constraint\n\n(If you are dealing with a generated constraint name like $2, don't forget\nthat\nyou'll need to double-quote it to make it a valid identifier.)\n -- I don't think current releases generate names like that anymore?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/ddl-rowsecurity.html\n\n5.8. Row Security Policies\n -- A general note: interaction of row security with search_path is not\n documented at all, but it may be important is some cases, like using\n functions in row security policies.\n\n----- <in the same section> ------\n\nWe can then see that an administrator connecting over a network will not see\nany records, due to the restrictive policy:\n\n=> SELECT current_user;\n current_user\n--------------\n admin\n(1 row)\n\n=> select inet_client_addr();\n inet_client_addr\n------------------\n 127.0.0.1\n(1 row)\n\n=> SELECT current_user;\n current_user\n--------------\n admin\n -- \"SELECT current_user;\" twice (I guess first one should have been psql\n-h).\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/dml-update.html\n\n6.2. Updating Data\n\nOnly if you have a primary key in the table (independent of whether you\ndeclared it or not) can you reliably address individual rows by choosing a\ncondition that matches the primary key.\n -- If it's about relational theory here, it's candidate key, actually (and\n there could be more that one).\n\nGraphical database access tools rely on this fact to allow you to update\nrows\nindividually.\n -- Is it certain there's no tool out there that uses \"WHERE CURRENT OF\ncursor\"\n for that, for instance? So, perhaps, change it to \"usually rely\" or\n\"Many\n graphical...\"?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/queries-table-expressions.html\n\n7.2. Table Expressions\n\nTrivial table expressions simply refer to a table on disk, a so-called base\ntable, but more complex expressions can be used to modify or combine base\ntables in various ways.\n -- Formally, referenced \"tables\" may be [materialized] views, etc.\n And the same, below:\n\nA table reference can be a table name (possibly schema-qualified), or a\nderived\ntable such as a subquery, a JOIN construct, or complex combinations of\nthese.\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/queries-table-expressions.html#QUERIES-FROM\n\n7.2.1.5. LATERAL Subqueries\n -- This section is yet another place where SQL style could use\nunification.\n\nFor example, if get_product_names() returns the names of products made by a\nmanufacturer, but some manufacturers in our table currently produce no\nproducts, we could find out which ones those are like this:\n\nSELECT m.name\n FROM manufacturers m LEFT JOIN LATERAL get_product_names(m.id) pname ON\ntrue\nWHERE pname IS NULL;\n -- Is it really a good example? A \"groupwise maximum\" would be much better\n one, IMHO. Besides, the query could have been (more naturally) written\nas:\n\n SELECT m.name\n FROM manufacturers\n WHERE EXISTS (\n SELECT 1\n FROM get_product_names(m.id)\n )\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/datatype-character.html\n\n8.3. Character Types\n\nSQL defines two primary character types: character varying(n) and\ncharacter(n),\nwhere n is a positive integer.\n -- SQL standard, perhaps?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/functions-math.html#FUNCTIONS-MATH-FUNC-TABLE\n\nTable 9.5. Mathematical Functions\n\nIn div(y numeric, x numeric) example:\ndiv(9,4)\n -- No space after the comma.\n\n----- <in the same section> ------\n\nmod(9,4)\n -- The same as above.\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE\n\nTable 9.55. General-Purpose Aggregate Functions\n\nbit_and -- the bitwise AND of all non-null input values, or null if none\nbit_or -- the bitwise OR of all non-null input values, or null if none\nbool_and -- true if all input values are true, otherwise false\n -- Descriptions of NULL handling are inconsistent: either the one in bit_*\n should be removed, or it should be added everywhere except in\nnon-strict\n functions?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/functions-aggregate.html\n9.20. Aggregate Functions\n\nUsers accustomed to working with other SQL database management systems might\nbe\ndisappointed by the performance of the count aggregate when it is applied to\nthe\nentire table.\n -- Which modern DBMS(s) is that about? Perhaps, the note could be removed?\n\n----- <in the same section> ------\n\nThis ordering is unspecified by default, but can be controlled by writing an\nORDER BY clause within the aggregate call, as shown in Section 4.2.7.\nAlternatively, supplying the input values from a sorted subquery will\nusually\nwork. For example:\n\nSELECT xmlagg(x) FROM (SELECT x FROM test ORDER BY y DESC) AS tab;\n\nBeware that this approach can fail if the outer query level contains\nadditional\nprocessing, such as a join, because that might cause the subquery's output\nto be\nreordered before the aggregate is computed.\n -- Perhaps, as the reliable way exists, the \"dangerous\" one could be\nremoved?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/functions-srf.html\n\n9.24. Set Returning Functions\n\nIn the example:\n-- basic usage\nSELECT generate_subscripts('{NULL,1,NULL,2}'::int[], 1) AS s;\n -- Why not:\n SELECT n\n FROM generate_subscripts('{NULL,1,NULL,2}'::int[], 1) AS s(n);\n\n----- <in the same section> ------\n\nSELECT a AS array, s AS subscript, a[s] AS value\nFROM (SELECT generate_subscripts(a, 1) AS s, a FROM arrays) foo;\n -- IMO, bad style: SRF call in the select list + implicit cross join + no\n AS before \"foo\", but used in every field alias; besides, \"array\" and\n \"value\" are keywords.\n\n----- <in the same section> ------\n\nCREATE OR REPLACE FUNCTION unnest2(anyarray)\n -- The same bad style as above.\n\n----- <in the same section> ------\n\nSELECT * FROM pg_ls_dir('.') WITH ORDINALITY AS t(ls,n);\n -- Nobody but a superuser can try this example (besides, the output is\nquite\n long). Why not come up with a better one?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/functions-info.html#FUNCTIONS-INFO-ACCESS-TABLE\n\nAfter Table 9.64. Access Privilege Inquiry Functions, in has_table_privilege\ndescription:\n\n(Thus, there are actually six variants of has_table_privilege, which can be\ndistinguished by the number and types of their arguments.)\n -- This note (describing an implementation detail) is present here, but\nnot\n for the other has_* functions. Perhaps, it could be removed or\ngeneralized?\n\n----- <in the same section> ------\n\nThe desired access privilege type is specified by a text string, which must\nevaluate to one of the values SELECT, INSERT, UPDATE, DELETE, TRUNCATE,\nREFERENCES, or TRIGGER. Optionally, WITH GRANT OPTION can be added to a\nprivilege type to test whether the privilege is held with grant option.\nAlso,\nmultiple privilege types can be listed separated by commas, in which case\nthe\nresult will be true if any of the listed privileges is held.\n -- The third sentence contradicts the first one (\"must evaluate to one\" vs\n\"\n \"multiple privilege types can be listed\")?\n\n----- <in the same section> ------\n\nhas_sequence_privilege checks whether a user can access a sequence in a\nparticular way. The possibilities for its arguments are analogous to\nhas_table_privilege. The desired access privilege type must evaluate to one\nof\nUSAGE, SELECT, or UPDATE.\n -- It also supports combinations of privileges. Besides, the support of\n optional WITH GRANT OPTION (as well as in the other similar functions)\n is not entirely clear from the description, IMHO.\n\n----- <in the same section> ------\n -- A note on style here --- in that section, there are several paragraphs\nof\n the common form:\n\n\"XXX checks whether a user can access a YYY in a particular way. Its\nargument\npossibilities are analogous to has_table_privilege. The desired access\nprivilege\ntype must evaluate to ZZZ.\"\n -- Could all of these be rewritten in a better way?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/functions-info.html#FUNCTIONS-TXID-SNAPSHOT-PARTS\n\nTable 9.75. Snapshot Components\n\nIn the xip_list description:\n\nThe list includes only those active txids between xmin and xmax;\n -- Is this correct English?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/functions-admin.html#FUNCTIONS-ADMIN-BACKUP\n\n9.26.3. Backup Control Functions\n\npg_current_wal_lsn displays the current write-ahead log write location in\nthe\nsame format used by the above functions.\n -- \"in the same format _as_ used\", perhaps?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/functions-event-triggers.html#PG-EVENT-TRIGGER-SQL-DROP-FUNCTIONS\n\n9.28.2. Processing Objects Dropped by a DDL Command\n\nIn example of \"CREATE FUNCTION test_event_trigger_for_drops()\":\n END LOOP;\nEND\n$$;\n -- Style nitpick: no \";\" after the last END, unlike in other examples.\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/typeconv-func.html\n\nExample 10.7. Variadic Function Resolution\n\nCREATE FUNCTION public.variadic_example(VARIADIC numeric[]) RETURNS int\n LANGUAGE sql AS 'SELECT 1';\nCREATE FUNCTION\n -- \"CREATE FUNCTION\" is both input SQL and psql output, hardly\ndistinguishable.\n Besides, the function body is not dollar-quoted (bad style). The same\ngoes\n for the following functions in the example.\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/indexes-bitmap-scans.html\n\n11.5. Combining Multiple Indexes\n\nFor example, given an index on (a, b) a query condition like WHERE a = 5 AND\nb =\n6 could use the index, but a query like WHERE a = 5 OR b = 6 could not\ndirectly\nuse the index.\n -- \"could not directly use\" is vague, IMO (i.e. PostgreSQL actually can\nand\n sometimes will use an index like that for the query).\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/indexes-partial.html\n\n11.8. Partial Indexes\n\nMatching takes place at query planning time, not at run time. As a result,\nparameterized query clauses do not work with a partial index. For example a\nprepared query with a parameter might specify “x < ?” which will never imply\n“x < 2” for all possible values of the parameter.\n -- First of all, parameters syntax in postgres is \"$n\", not \"?\"; then,\npartial\n indexes work just fine with parameterization or prepared statements?\nE.g.:\n CREATE TABLE a(b int, c int);\n CREATE INDEX ON a(b) WHERE c > 2;\n PREPARE foo(int) AS SELECT b FROM a WHERE c > $1 AND b = 15;\n EXPLAIN EXECUTE foo(3); -- Can use the index\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/textsearch-intro.html\n\n12.1. Introduction\n\nTextual search operators have existed in databases for years. PostgreSQL has\n~,\n~*, LIKE, and ILIKE operators for textual data types, but they lack many\nessential properties required by modern information systems:\n -- Honestly, the sentence reads like an ad to me. ;)\n\nIt is possible to use OR to search for multiple derived forms, but this is\ntedious and error-prone (some words can have several thousand derivatives).\n -- It's also possible to use \"|\" in regexps for the purpose (and much\neasier\n to list thousands of derivatives this way).\n\nThey tend to be slow because there is no index support, so they must process\nall\ndocuments for every search.\n -- There's pg_trgm, now.\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/textsearch-intro.html#TEXTSEARCH-MATCHING\n\n12.1.2. Basic Text Matching\n\nThere are functions to_tsquery, plainto_tsquery, and phraseto_tsquery that\nare\nhelpful in converting user-written text into a proper tsquery, primarily by\nnormalizing words appearing in the text.\n -- There's also websearch_to_tsquery now, is it relevant here?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/textsearch-tables.html\n\n12.2.1. Searching a Table\n\nA more complex example is to select the ten most recent documents that\ncontain\ncreate and table in the title or body:\n\nSELECT title\nFROM pgweb\nWHERE to_tsvector(title || ' ' || body) @@ to_tsquery('create & table')\nORDER BY last_mod_date DESC\nLIMIT 10;\n -- It's rather create and table in the title and/or body?\n E.g. it matches with:\n WITH pgweb(title, body, last_mod_date) AS (VALUES ('create', 'table',\n'2020-01-01'))\n\n----- <in the same section> ------\n\nFor clarity we omitted the coalesce function calls which would be needed to\nfind\nrows that contain NULL in one of the two fields.\n -- \"title || ' ' || body\" above could be replaced with, say:\n \"concat_ws(' ', title, body)\" to avoid the problem, and this paragraph\n removed.\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES\n\n12.3.2. Parsing Queries\n\nSELECT websearch_to_tsquery('english', 'The fat rats');\n websearch_to_tsquery\n----------------------\n 'fat' & 'rat'\n(1 row)\n-- All the examples of websearch_to_tsquery have \"(1 row)\" after each one,\nwhile\n the ones for previous functions lack it.\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY\n\n12.4.2. Manipulating Queries\n\ntsquery && tsquery\n Returns the AND-combination of the two given queries.\n -- Is this \"given\" a good English (there are several similar sentences\n below)?\n\n----- <in the same section> ------\n\nSELECT to_tsquery('fat') <-> to_tsquery('cat | rat');\n ?column?\n-----------------------------------\n 'fat' <-> 'cat' | 'fat' <-> 'rat'\n -- This returns \"'fat' <-> ( 'cat' | 'rat' )\" now.\n\nReturns a query that searches for a match to the first given query followed\nby a\nmatch to the second given query at a distance of at distance lexemes, using\nthe\n<N> tsquery operator.\n -- Seems like \"at a distance of at distance lexemes\" has an extra \"at\"?\n\n----- <in the same section> ------\n\nSELECT numnode(plainto_tsquery('the any'));\nNOTICE: query contains only stopword(s) or doesn't contain lexeme(s),\nignored\n numnode\n---------\n 0\n -- The actual NOTICE spelling now is:\n \"text-search query contains only stop words or doesn't contain lexemes,\n ignored\"\n\n----- <in the same section> ------\n\nSELECT querytree(to_tsquery('!defined'));\n querytree\n-----------\n\n -- This returns \"T\" now.\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/textsearch-dictionaries.html#TEXTSEARCH-SYNONYM-DICTIONARY\n\n12.6.3. Synonym Dictionary\n\nmydb=# CREATE TEXT SEARCH DICTIONARY syn (template=synonym,\nsynonyms='synonym_sample');\n -- Why is this \"mydb=#\" prefix in all the examples here (previous ones\ndon't\n have it)?\n\nSELECT ts_lexize('syn','indices');\n -- No space after the comma in the function argument list (there are\nseveral\n like this below).\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/textsearch-dictionaries.html#TEXTSEARCH-THESAURUS\n\n12.6.4.1. Thesaurus Configuration\n\nCREATE TEXT SEARCH DICTIONARY thesaurus_simple (\n TEMPLATE = thesaurus,\n DictFile = mythesaurus,\n Dictionary = pg_catalog.english_stem\n);\n -- Why TEMPLATE is spelled all-CAPS here, while DictFile is camel-case\n(seems\n inconsistent style)?\n\n----- <in the same section> ------\n\nThesauruses are used during indexing so any change in the thesaurus\ndictionary's\nparameters requires reindexing. For most other dictionary types, small\nchanges\nsuch as adding or removing stopwords does not force reindexing.\n -- Is it \"stop words\" or \"stopwords\", or \"stop-words\"? Spelling seems to\nbe\n inconsistent in the documentation (and error messages).\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/textsearch-indexes.html\n\n12.9. GIN and GiST Index Types\n\nA GiST index can be covering, i.e. use the INCLUDE clause. Included columns\ncan\nhave data types without any GiST operator class. Included attributes will be\nstored uncompressed.\n -- Is this really relevant here (it's the same for any GiST index)?\n\n----- <in the same section> ------\n\nSince random access to table records is slow, this limits the usefulness of\nGiST\nindexes.\n -- Or it might not be --- if it's SSD, or the index pages are in RAM.\n\n----- <in the same section> ------\n\nNote that GIN index build time can often be improved by increasing\nmaintenance_work_mem, while GiST index build time is not sensitive to that\nparameter.\n -- Buffered GiST build does depend on maintenance_work_mem value.\n\n----- <in the same section> ------\n\nPartitioning can be done at the database level using table inheritance, or\nby\ndistributing documents over servers and collecting external search results,\ne.g.\nvia Foreign Data access.\n -- Why is it \"table inheritance\" here, not declarative partitioning?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/textsearch-psql.html\n\n12.10. psql Support\n\n-- All of this is documented in psql reference, and examples here are\nlengthy.\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/transaction-iso.html#XACT-REPEATABLE-READ\n\n13.2.2. Repeatable Read Isolation Level\n\nThe Repeatable Read mode provides a rigorous guarantee that each transaction\nsees a completely stable view of the database. However, this view will not\nnecessarily always be consistent with some serial (one at a time) execution\nof\nconcurrent transactions of the same level. For example, even a read only\ntransaction at this level may see a control record updated to show that a\nbatch\nhas been completed but not see one of the detail records which is logically\npart\nof the batch because it read an earlier revision of the control record.\n -- The example is very vague by itself, IMO. I suppose it's a reference to\n https://wiki.postgresql.org/wiki/SSI#Deposit_Report , but is it really\n expected a reader will understand that from the above paragraph?!\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/transaction-iso.html#XACT-SERIALIZABLE\n\n13.2.3. Serializable Isolation Level\n\nSuppose that serializable transaction A computes:\n\n<skip>\n\nConcurrently, serializable transaction B computes:\n\n<skip>\n\nbut since there is no serial order of execution consistent with the result,\nusing Serializable transactions will allow one transaction to commit and\nwill\nroll the other back with this message:\n -- Inconsistent capitalization of Serializable?\n\n----- <in the same section> ------\n\nIf you explicitly request a SERIALIZABLE READ ONLY DEFERRABLE transaction,\nit\nwill block until it can establish this fact.\n -- Actually, the first query in such a transaction will block. Perhaps, it\n should be clarified?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-ROWS\n\n13.3.2. Row-Level Locks\n\nThe FOR UPDATE lock mode is also acquired by any DELETE on a row, and also\nby an\nUPDATE that modifies the values on certain columns.\n -- on certain -> of certain?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/explicit-locking.html#ADVISORY-LOCKS\n\n13.3.5. Advisory Locks\n\nLike all locks in PostgreSQL, a complete list of advisory locks currently\nheld\nby any session can be found in the pg_locks system view.\n -- Row-level locks are not there --- perhaps, \"Like all locks ...\" part\nis\n just unnecessary?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/using-explain.html\n\n14.1. Using EXPLAIN\n\nExamples in this section are drawn from the regression test database after\ndoing\na VACUUM ANALYZE, using 9.3 development sources.\n -- Which is EOL by now. Isn't it a time to update?\n\n----- <in the same section> ------\n\nYou should be able to get similar results if you try the examples yourself,\nbut\nyour estimated costs and row counts might vary slightly because ANALYZE's\nstatistics are random samples rather than exact, and because costs are\ninherently somewhat platform-dependent.\n -- What does it mean (that some planner cost constants are\nplatform-dependent)?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/using-explain.html#USING-EXPLAIN-BASICS\n\n14.1.1. EXPLAIN Basics\n\n(Every correct plan will output the same row set, we trust.)\n -- Which is outright wrong:\n SELECT *\n FROM any_table\n WHERE random() < 0.1;\n\n----- <in the same section> ------\nReturning to our example:\n -- Is it really worth repeating it in full (it's not that far above)?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/using-explain.html#USING-EXPLAIN-ANALYZE\n\n14.1.2. EXPLAIN ANALYZE\n\nThe numbers provided by BUFFERS help to identify which parts of the query\nare\nthe most I/O-intensive.\n -- No mention of what these numbers actually *are* (pages / blocks).\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/planner-stats.html#PLANNER-STATS-EXTENDED\n\n14.2.2.1. Functional Dependencies\n\nIn a fully normalized database, functional dependencies should exist only on\nprimary keys and superkeys. However, in practice many data sets are not\nfully\nnormalized for various reasons; intentional denormalization for performance\nreasons is a common example.\n -- Confusing terminology: IIRC, modern normalization theory doesn't use\nPKs\n (but \"candidate keys\"). Besides, \"denormalization\" is confusing by\nitself.\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/parallel-safety.html\n\n15.4.1. Parallel Labeling for Functions and Aggregates\n\nThe following operations are always parallel restricted.\n -- Should end with \":\" instead of \".\"?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/install-procedure.html\n\n16.4. Installation Procedure\n\nThe standard installation provides all the header files needed for client\napplication development as well as for server-side program development, such\nas\ncustom functions or data types written in C. (Prior to PostgreSQL 8.0, a\nseparate make install-all-headers command was needed for the latter, but\nthis\nstep has been folded into the standard install.)\n -- I guess the last sentence is not relevant anymore.\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/installation-platform-notes.html#INSTALLATION-NOTES-CYGWIN\n\n16.7.2. Cygwin\n\nThe adduser command is not supported; use the appropriate user management\napplication on Windows NT, 2000, or XP. Otherwise, skip this step.\n\nThe su command is not supported; use ssh to simulate su on Windows NT, 2000,\nor\nXP. Otherwise, skip this step.\n -- AFAIK, all these operating systems are dead.\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/install-windows-full.html#id-1.6.4.8.8\n\n17.1.1. Requirements\n\nActiveState TCL\n\n Required for building PL/Tcl (Note: version 8.4 is required, the free\nStandard\n Distribution is sufficient).\n -- version 8.4 or later, perhaps?\n\n----- <in the same section> ------\nNote\n The obsolete winflex binaries distributed on the PostgreSQL FTP site and\n referenced in older documentation will fail with “flex: fatal internal\nerror,\n exec failed” on 64-bit Windows hosts. Use Flex from MSYS instead.\n -- Is this note still relevant?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/creating-cluster.html\n\n18.2. Creating a Database Cluster\n\nAfter initialization, a database cluster will contain a database named\npostgres,\nwhich is meant as a default database for use by utilities, users and third\nparty\napplications. The database server itself does not require the postgres\ndatabase\nto exist, but many external utility programs assume it exists. Another\ndatabase\ncreated within each cluster during initialization is called template1.\n -- Why template0 is not mentioned at all in this subchapter?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/kernel-resources.html#SYSVIPC\n\n18.4.1. Shared Memory and Semaphores\n\nThe maximum number of semaphores in the system is set by SEMMNS, which\nconsequently must be at least as high as max_connections plus\nautovacuum_max_workers plus max_wal_senders, plus max_worker_processes, plus\none\nextra for each 16 allowed connections plus workers (see the formula in Table\n18.1).\n -- Why duplicate formulas (in the table and here)?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/upgrading.html#UPGRADING-VIA-PGDUMPALL\n\n18.6.1. Upgrading Data via pg_dumpall\n\nOne upgrade method is to dump data from one major version of PostgreSQL and\nreload it in another — to do this, you must use a logical backup tool like\npg_dumpall; file system level backup methods will not work.\n -- IMO, it would be nice to call dumps dumps, not \"logical backups\".\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/runtime-config-developer.html\n\n19.17. Developer Options\n\ntrace_lock_oidmin (integer)\n\n If set, do not trace locks for tables below this OID. (use to avoid output\n on system tables)\n -- Incorrect \".\" position, should be moved to the end of the sentence.\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/role-attributes.html\n\n21.2. Role Attributes\n\n(except for superusers, since those bypass all permission checks)\n -- Repeated several times in this subchapter (could it be rephrased?).\n\n----- <in the same section> ------\n\nThe password and md5 authentication methods make use of passwords. Database\npasswords are separate from operating system passwords.\n -- What about SCRAM (scram-sha-256)?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/manage-ag-dropdb.html\n\n22.5. Destroying a Database\n\ntemplate1 would be the only option for dropping the last user database of a\ngiven cluster.\n -- What about using \"postgres\" (or even template0, if one allows\nconnections\n to it) database?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/manage-ag-tablespaces.html\n\n22.6. Tablespaces\n\nNote that in PostgreSQL 9.1 and earlier you will also need to update the\npg_tablespace catalog with the new locations. (If you do not, pg_dump will\ncontinue to output the old tablespace locations.)\n -- Outdated comment (9.1 is EOL).\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/maintenance.html\n\nChapter 24. Routine Database Maintenance Tasks\n\nPostgreSQL, like any database software, requires that certain tasks be\nperformed\nregularly to achieve optimum performance.\n -- Why not remove \"like any database software\"? I really doubt anyone\nchecked\n every \"database software\" in the world (and, say, sqlite comes to\nmind).\n Besides, how is that relevant to the point made here?\n\n----- <in the same section> ------\n\nThe other main category of maintenance task is periodic “vacuuming” of the\ndatabase.\n -- \"of maintenance tasks\" (plural), perhaps?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/routine-vacuuming.html#VACUUM-FOR-WRAPAROUND\n\n24.1.5. Preventing Transaction ID Wraparound Failures\n\nvacuum_freeze_min_age controls how old an XID value has to be before rows\nbearing that XID will be frozen. Increasing this setting may avoid\nunnecessary\nwork if the rows that would otherwise be frozen will soon be modified again,\nbut\ndecreasing this setting increases the number of transactions that can elapse\nbefore the table must be vacuumed again.\n -- Isn't it \"decreasing this setting _decreases_ the number of\n transactions...\"?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/backup.html\n\nChapter 25. Backup and Restore\n\nAs with everything that contains valuable data, PostgreSQL databases should\nbe\nbacked up regularly.\n -- IMNSHO, the whole point of the chapter is backwards. If the data is\n valuable, one wants to prevent (or recover) from its loss. Backups are\njust\n a *mean* for that, while data loss avoidance is the *goal*. Enters\ndisaster\n recovery (and more broadly business continuity). Two metrics are\n fundamental to that: RPO and RTO. Using pg_dump, one cannot even get\n predictable values for those in any non-trivial case. Therefore, \"25.1.\nSQL\n Dump\" should not be first and foremost in the chapter (if mentioned at\n all); and the whole chapter better be written with the above in mind.\nAt\n least, it would be nice if dumps were called dumps, not backups, as\nwell as\n the process of making those was called dumping in \"25.1. SQL Dump\".\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/continuous-archiving.html#BACKUP-BASE-BACKUP\n\n25.3.2. Making a Base Backup\n\nTo aid you in doing this, the base backup process creates a backup history\nfile\nthat is immediately stored into the WAL archive area.\n -- The sentence isn't clear --- what's meant by \"WAL archive area\" here?\n\n----- <in the same section> ------\n\nIf you used the label to identify the associated dump file, then the\narchived\nhistory file is enough to tell you which dump file to restore.\n -- What is meant by \"dump file\" here?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/continuous-archiving.html#BACKUP-LOWLEVEL-BASE-BACKUP\n\n25.3.3.1. Making a Non-Exclusive Low-Level Backup\n\nOn a primary, if archive_mode is enabled and the wait_for_archive parameter\nis\ntrue, pg_stop_backup does not return until the last segment has been\narchived.\n -- It's not entirely clear that wait_for_archive is pg_stop_backup\nparameter,\n and even if yes, which one is it (first or second).\n\n----- <in the same section> ------\n\n25.3.3.3. Backing Up the Data Directory\n\nThis is easy to arrange if pg_wal/ is a symbolic link pointing to someplace\noutside the cluster directory, which is a common setup anyway for\nperformance\nreasons.\n -- Perhaps, this \"common\" setup should be also mentioned / recommended\n elsewhere, then?\n\n----- <in the same section> ------\n\nIn case of confusion it is therefore possible to look inside a backup file\nand\ndetermine exactly which backup session the dump file came from.\n -- \"inside a backup _label_ file\", perhaps? And what's meant by \"dump\"\nhere?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/continuous-archiving.html#BACKUP-PITR-RECOVERY\n\n25.3.4. Recovering Using a Continuous Archive Backup\n\nIt is important that the command return nonzero exit status on failure.\n -- \"returns\", perhaps?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/continuous-archiving.html#BACKUP-TIPS\n\n25.3.6.1. Standalone Hot Backups\n\nWith this preparation, a backup can be taken using a script like the\nfollowing:\n -- The following is the recipe for an exclusive backup, which is\ndeprecated.\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/high-availability.html\n\nChapter 26. High Availability, Load Balancing, and Replication\n\nSome solutions are synchronous, meaning that a data-modifying transaction is\nnot\nconsidered committed until all servers have committed the transaction. This\nguarantees that a failover will not lose any data and that all load-balanced\nservers will return consistent results no matter which server is queried.\n -- The last sentence confuses distributed durability (\"guarantees that a\n failover will not lose any data\") with distributed atomic visibility\n(\"all\n load-balanced servers will return consistent results\") --- the latter\nis\n impossible to guarantee by any method of replication provided by\n PostgreSQL.\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/log-shipping-alternative.html\n\n26.4. Alternative Method for Log Shipping\n\nNote that in this mode, the server will apply WAL one file at a time, so if\nyou\nuse the standby server for queries (see Hot Standby), there is a delay\nbetween\nan action in the master and when the action becomes visible in the standby,\ncorresponding the time it takes to fill up the WAL file.\n -- Is it \"corresponding the time\" or \"corresponding to the time\"?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/log-shipping-alternative.html#WARM-STANDBY-RECORD\n\n26.4.2. Record-Based Log Shipping\n\nStarting with PostgreSQL version 9.0, you can use streaming replication (see\nSection 26.2.5) to achieve the same benefits with less effort.\n -- The described method seems to be quite non-trivial, and, it seems,\nprovides\n no benefits over streaming replication. Perhaps, this section should be\n removed altogether?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/hot-standby.html#HOT-STANDBY-ADMIN\n\n26.5.3. Administrator's Overview\n\nWAL file control commands will not work during recovery, e.g.\npg_start_backup,\npg_switch_wal etc.\n -- pg_start_backup does work during recovery (for non-exclusive backups).\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/wal-reliability.html\n\n29.1. Reliability\n\nWhile forcing data to the disk platters periodically might seem like a\nsimple\noperation, it is not. Because disk drives are dramatically slower than main\nmemory and CPUs, several layers of caching exist between the computer's main\nmemory and the disk platters.\n -- Perhaps, \"disk platters\" (used twice here) could be improved (SSDs\ndon't\n have any)?\n\n----- <in the same section> ------\n\nThese commands are not directly accessible to PostgreSQL, but some file\nsystems\n(e.g., ZFS, ext4) can use them to flush data to the platters on\nwrite-back-enabled drives.\n -- Perhaps, \"platters\" could be improved (SSDs don't have any)?\n\n----- <in the same section> ------\n\nAnother risk of data loss is posed by the disk platter write operations\nthemselves. Disk platters are divided into sectors, commonly 512 bytes each.\n -- Perhaps, \"platters\" / \"Disk platters\" could be improved (SSDs don't\nhave\n any)?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/logical-replication.html\n\nChapter 30. Logical Replication\n\nThe subscriber applies the data in the same order as the publisher so that\ntransactional consistency is guaranteed for publications within a single\nsubscription.\n -- \"transactional consistency\" is vague. Perhaps, a warning analogous\n to the one in\nhttps://www.postgresql.org/docs/current/applevel-consistency.html#SERIALIZABLE-CONSISTENCY\n could be added here for clarification?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/logical-replication-architecture.html\n\n30.5.1. Initial Snapshot\n\nLogical replication starts by copying a snapshot of the data on the\npublisher\ndatabase.\n -- \"from the publisher\", perhaps?\n\n----- <in the same section> ------\n\nThe subscriber applies data in the order in which commits were made on the\npublisher so that transactional consistency is guaranteed for the\npublications\nwithin any single subscription.\n -- \"transactional consistency\" is vague (not clear if it's atomic, here)?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/libpq-status.html\n\n33.2. Connection Status Functions\n\n(server_encoding, TimeZone, and integer_datetimes were not reported by\nreleases\nbefore 8.0; standard_conforming_strings was not reported by releases before\n8.1;\nIntervalStyle was not reported by releases before 8.4; application_name was\nnot\nreported by releases before 9.0.)\n -- All of these releases are very old --- perhaps, this could be removed?\n\nPre-3.0-protocol servers do not report parameter settings, but libpq\nincludes\nlogic to obtain values for server_version and client_encoding anyway.\n -- Pre-3.0-protocol servers are very old --- perhaps, this could be\nremoved?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/libpq-async.html\n\n33.4. Asynchronous Command Processing\n\nLike PQprepare, it will not work on 2.0-protocol connections.\n -- The chapter has several warnings like this. Perhaps (as protocol 2.0 is\n very old) these could be removed?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/lo-interfaces.html#LO-CREATE\n\n34.3.1. Creating a Large Object\n\nlo_create is new as of PostgreSQL 8.1; if this function is run against an\nolder\nserver version, it will fail and return InvalidOid.\n -- PostgreSQL 8.1 is very old --- perhaps, the warning could be removed?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/xfunc-sql.html\n\n37.5. Query Language (SQL) Functions\n\nAlternatively, an SQL function can be declared to return a set (that is,\nmultiple rows) by specifying the function's return type as SETOF sometype,\nor\nequivalently by declaring it as RETURNS TABLE(columns).\n -- \"an SQL function\" here...\n\nAlternatively, if you want to define a SQL function that performs actions\nbut\nhas no useful value to return, you can define it as returning void.\n -- But \"a SQL function\" here. Is it correct?\n\n----- <in the same section> ------\n\nCREATE FUNCTION clean_emp() RETURNS void AS '\n DELETE FROM emp\n WHERE salary < 0;\n' LANGUAGE SQL;\n -- Why not use dollar-quoting here (as recommended in the text below)?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/xfunc-sql.html#XFUNC-SQL-FUNCTION-ARGUMENTS\n\n37.5.1. Arguments for SQL Functions\n\nThe ability to use names to reference SQL function arguments was added in\nPostgreSQL 9.2. Functions to be used in older servers must use the $n\nnotation.\n -- Perhaps (as 9.2 is EOL), this note could be removed?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/xfunc-sql.html#XFUNC-SQL-BASE-FUNCTIONS\n\n37.5.2. SQL Functions on Base Types\n\n-- Alternative syntax for string literal:\nCREATE FUNCTION one() RETURNS integer AS '\n SELECT 1 AS result;\n' LANGUAGE SQL;\n -- What's the point of the \"alternative syntax\" example (besides\nthickening\n the manual)?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/xfunc-c.html#id-1.8.3.13.13\n\n37.10.9. Polymorphic Arguments and Return Types\n\nThere are two routines provided in fmgr.h to allow a version-1 C function to\ndiscover the actual data types of its arguments and the type it is expected\nto\nreturn.\n -- Remove \"version-1\", perhaps?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/extend-extensions.html#id-1.8.3.20.11\n\n37.17.1. Extension Files\n\nThe CREATE EXTENSION command relies on a control file for each extension,\nwhich\nmust be named the same as the extension with a suffix of .control, and must\nbe\nplaced in the installation's SHAREDIR/extension directory.\n -- In the other places in documentation, it's $SHAREDIR (with dollar).\n\nBy default, the script file(s) are also placed in the SHAREDIR/extension\ndirectory; but the control file can specify a different directory for the\nscript\nfile(s).\n -- In the other places in documentation, it's $SHAREDIR (with dollar).\n\nUnless an absolute path is given, the name is relative to the installation's\nSHAREDIR directory.\n -- In the other places in documentation, it's $SHAREDIR (with dollar).\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/rules-views.html#id-1.8.6.7.7\n\n40.2.3. The Power of Views in PostgreSQL\n\nThe benefit of implementing views with the rule system is, that the planner\nhas\nall the information about which tables have to be scanned plus the\nrelationships\nbetween these tables plus the restrictive qualifications from the views plus\nthe\nqualifications from the original query in one single query tree.\n -- The comma is not needed here?\n\n----- <in the same section> ------\n\nAnd the rule system as implemented in PostgreSQL ensures, that this is all\ninformation available about the query up to that point.\n -- The comma is not needed here?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/rules-triggers.html\n\n40.7. Rules Versus Triggers\n\nSo if many rows are affected in one statement, a rule issuing one extra\ncommand\nis likely to be faster than a trigger that is called for every single row\nand\nmust re-determine what to do many times.\n -- There are triggers with transition relations now --- perhaps, this\nshould\n be corrected?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/plpgsql-trigger.html#PLPGSQL-TRIGGER-EXAMPLE\n\nExample 42.3. A PL/pgSQL Trigger Function\n\nlast_date timestamp,\n -- Why not timestamptz?\n\nNEW.last_date := current_timestamp;\n -- current_timestamp returns timestamptz (which should be used here).\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/plpgsql-trigger.html#PLPGSQL-TRIGGER-AUDIT-EXAMPLE\n\nExample 42.4. A PL/pgSQL Trigger Function for Auditing\n\nCREATE TABLE emp_audit(\n operation char(1) NOT NULL,\n stamp timestamp NOT NULL,\n -- Should be timestamptz (BTW, now() is used later to fill it).\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/plpgsql-trigger.html#PLPGSQL-VIEW-TRIGGER-AUDIT-EXAMPLE\n\nExample 42.5. A PL/pgSQL View Trigger Function for Auditing\n\nCREATE TABLE emp_audit(\n ...\n stamp timestamp NOT NULL\n -- Should be timestamptz\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/plpgsql-trigger.html#PLPGSQL-TRIGGER-SUMMARY-EXAMPLE\n\nExample 42.6. A PL/pgSQL Trigger Function for Maintaining a Summary Table\n\n <<insert_update>>\n LOOP\n UPDATE sales_summary_bytime\n SET amount_sold = amount_sold + delta_amount_sold,\n units_sold = units_sold + delta_units_sold,\n amount_cost = amount_cost + delta_amount_cost\n WHERE time_key = delta_time_key;\n\n EXIT insert_update WHEN found;\n\n BEGIN\n INSERT INTO sales_summary_bytime (\n time_key,\n amount_sold,\n units_sold,\n amount_cost)\n VALUES (\n delta_time_key,\n delta_amount_sold,\n delta_units_sold,\n delta_amount_cost\n );\n\n EXIT insert_update;\n\n EXCEPTION\n WHEN UNIQUE_VIOLATION THEN\n -- do nothing\n END;\n END LOOP insert_update;\n -- The above works only in READ COMMITTED --- perhaps, it should be\nmentioned?\n Or just replaced with INSERT ... ON CONFLICT ... DO UPDATE?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/plpgsql-trigger.html#PLPGSQL-TRIGGER-AUDIT-TRANSITION-EXAMPLE\n\nExample 42.7. Auditing with Transition Tables\n\nCREATE TABLE emp_audit(\n operation char(1) NOT NULL,\n stamp timestamp NOT NULL,\n -- Should be timestamptz\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/plpgsql-implementation.html#PLPGSQL-PLAN-CACHING\n\n42.11.2. Plan Caching\n\nCREATE FUNCTION logfunc2(logtxt text) RETURNS void AS $$\n DECLARE\n curtime timestamp;\n BEGIN\n curtime := 'now';\n INSERT INTO logtable VALUES (logtxt, curtime);\n END;\n$$ LANGUAGE plpgsql;\n -- Why not timestamptz in the above?\n\n----- <in the same section> ------\n\nIn the case of logfunc1, the PostgreSQL main parser knows when analyzing the\nINSERT that the string 'now' should be interpreted as timestamp, because the\ntarget column of logtable is of that type. Thus, 'now' will be converted to\na\ntimestamp constant when the INSERT is analyzed, and then used in all\ninvocations\nof logfunc1 during the lifetime of the session.\n -- timestamp -> timestamptz?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/pltcl-functions.html\n\n43.2. PL/Tcl Functions and Arguments\n\nIn a nonstrict function, if the actual value of an argument is null, the\ncorresponding $n variable will be set to an empty string.\n -- It's \"n variable\" (without dollar).\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/pltcl-dbaccess.html\n\n43.5. Database Access from PL/Tcl\n\nFor example:\n spi_exec \"SELECT count(*) AS cnt FROM pg_proc\"\nwill set the Tcl variable $cnt to the number of rows in the pg_proc system\ncatalog.\n -- It's \"variable cnt\" (without dollar).\n\n----- <in the same section> ------\n\nWe need backslashes inside the query string given to spi_prepare to ensure\nthat\nthe $n markers will be passed through to spi_prepare as-is, and not replaced\nby\nTcl variable substitution.\n -- Perhaps, add that:\n {SELECT count(*) AS cnt FROM t1 WHERE num >= $1 AND num <= $2}\n could have been used instead (or use it instead and remove the\nparagraph)?\n\n----- <in the same section> ------\n\nquote string\n Doubles all occurrences of single quote and backslash characters in the\ngiven\n string.\n -- And indeed it does, so:\n set x {don't \\add \\ }\n elog NOTICE \"$x = [quote $x]\"\n Results in:\n NOTICE: don't \\add \\ = don''t \\\\add \\\\\n Which is not going to work correctly with default\nstandard_conforming_strings\n setting, and the following example is actually wrong:\n\n\"SELECT '[ quote $val ]' AS ret\"\n -- Should be \"SELECT E'[ quote $val ]' AS ret\" (or, perhaps, it's a bug in\n \"quote\" function?)\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/pltcl-trigger.html\n\n43.6. Trigger Functions in PL/Tcl\n\nThe information from the trigger manager is passed to the function body in\nthe\nfollowing variables:\n\n$TG_name\n -- It's \"TG_name\" (without dollar). The same goes for all the following\n variables.\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/pltcl-event-trigger.html\n\n43.7. Event Trigger Functions in PL/Tcl\n\n$TG_event\n -- It's \"TG_event\" (without dollar). The same goes for the following\nvariable.\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/plperl-funcs.html\n\n44.1. PL/Perl Functions and Arguments\n\nIt is usually most convenient to use dollar quoting (see Section 4.1.2.4)\nfor\nthe string constant. If you choose to use escape string syntax E'', you must\ndouble any single quote marks (') and backslashes (\\) used in the body of\nthe\nfunction (see Section 4.1.2.1).\n -- Perhaps, the last sentence (or both) could be removed (it's\nsufficiently\n described elsewhere; PL/Tcl and PL/Python chapters have no similar text\n about quoting)?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/sql-copy.html\n\nfilename\n\n The path name of the input or output file. An input file name can be an\n absolute or relative path, but an output file name must be an absolute\npath.\n Windows users might need to use an E'' string and double any backslashes\n used in the path name.\n -- But why they might need to use an E'' string (this is quite vague)?\n\nFREEZE\n This is intended as a performance option for initial data loading.\n -- But actually it's almost useless (as visibility map is not written\nby\n COPY FREEZE, therefore index-only scans don't work as intended, and\nthe\n next VACUUM will re-scan the whole table). Perhaps, add a note about\n that?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/sql-createconversion.html\n\nThe privileges required to create a conversion might be changed in a future\nrelease.\n -- But are still the same (looked back as far as 7.3). What's the use of\nthis\n warning (perhaps, it could be removed)?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/sql-createextension.html\n\nPostgreSQL will create the extension using details from the file\nSHAREDIR/extension/extension_name.control.\n -- In the other places in documentation, it's $SHAREDIR (with dollar).\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/sql-createforeigntable.html\n\nCREATE FOREIGN TABLE films (\n code char(5) NOT NULL,\n title varchar(40) NOT NULL,\n did integer NOT NULL,\n date_prod date,\n kind varchar(10),\n -- Perhaps, replace all the char types here with text + CHECKs (would be\nnice\n if the documentation adhered to\n https://wiki.postgresql.org/wiki/Don%27t_Do_This)?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/sql-createtable.html\n -- For all the \"Examples\" section: perhaps, replace all the char types\nhere\n with text + CHECKs (would be nice if the documentation adhered to\n https://wiki.postgresql.org/wiki/Don%27t_Do_This)?\n\nAlso:\n modtime timestamp DEFAULT current_timestamp\n -- Replace with timestamptz.\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/sql-createtransform.html\n\nSynopsis\n FROM SQL WITH FUNCTION from_sql_function_name [ (argument_type [, ...])\n],\n TO SQL WITH FUNCTION to_sql_function_name [ (argument_type [, ...]) ]\n -- It seems that a transform function might accept many arguments, but\nit's\n not documented like that below?\n\nfrom_sql_function_name[(argument_type [, ...])]\n It must take one argument of type internal and return type internal.\n -- [, ...] contradicts the description?\n\nto_sql_function_name[(argument_type [, ...])]\n It must take one argument of type internal and return the type that is\nthe\n type for the transform.\n -- [, ...] contradicts the description?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/sql-createview.html\n\nCREATE VIEW comedies AS\n SELECT f.*,\n country_code_to_name(f.country_code) AS country,\n (SELECT avg(r.rating)\n FROM user_ratings r\n WHERE r.film_id = f.id) AS avg_rating\n FROM films f\n WHERE f.kind = 'Comedy';\n -- Using AS for aliases (user_ratings AS r, films AS f) would be better\n style, IMO.\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/sql-dropfunction.html\n\n* The standard only allows one function to be dropped per command.\n -- The following items don't have points at the end.\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/sql-rollback-to.html\n\nThe SQL standard specifies that the key word SAVEPOINT is mandatory, but\nPostgreSQL and Oracle allow it to be omitted.\n -- Why do we need to document Oracle behavior here?\n\n----- <in the same section> ------\n\nAlso, SQL has an optional clause AND [ NO ] CHAIN which is not currently\nsupported by PostgreSQL.\n -- ISO SQL (from a draft of 2011) states: \"If AND CHAIN is specified, then\n <savepoint clause> shall not be specified.\" So, the sentence is\nincorrect?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/sql-select.html\n\n [ HAVING condition [, ...] ]\n -- There could be only one condition in HAVING, \"[, ...]\" is incorrect.\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE\n\nPrevious releases failed to preserve a lock which is upgraded by a later\nsavepoint. For example, this code:\n\n<skipped>\n\nwould fail to preserve the FOR UPDATE lock after the ROLLBACK TO. This has\nbeen\nfixed in release 9.3.\n -- 9.3 is already unsupported --- perhaps, the warning could be removed\nnow?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/sql-select.html#id-1.9.3.171.9\n\nExamples\n\nTo join the table films with the table distributors:\n\nSELECT f.title, f.did, d.name, f.date_prod, f.kind\n FROM distributors d, films f\n WHERE f.did = d.did\n -- Why not use explicit JOIN ... ON here? Also, there's no \";\" at the end,\n unlike in the following examples.\n\n----- <in the same section> ------\n\nSELECT kind, sum(len) AS total FROM films GROUP BY kind;\n -- Would be nice if examples were formatted in the same style (the\nfollowing\n ones, too).\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/sql-select.html#id-1.9.3.171.10\n\nNote that if a FROM clause is not specified, the query cannot reference any\ndatabase tables. For example, the following query is invalid:\n\nSELECT distributors.* WHERE distributors.name = 'Westward';\n\nPostgreSQL releases prior to 8.1 would accept queries of this form, and add\nan\nimplicit entry to the query's FROM clause for each table referenced by the\nquery. This is no longer allowed.\n -- 8.1 is unsupported for years. Perhaps, this warning could be removed?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/sql-selectinto.html\n\n [ HAVING condition [, ...] ]\n -- There could be only one condition in HAVING, \"[, ...]\" is incorrect.\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/sql-set.html\n\nSET TIME ZONE\n <skip>\nLOCAL\nDEFAULT\n Set the time zone to your local time zone (that is, the server's default\n value of timezone).\n -- Seems like it resets to the database / role default (if any of\nthose is\n set), instead.\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/sql-show.html\n\nThese variables can be set using the SET statement, by editing the\npostgresql.conf configuration file, through the PGOPTIONS environmental\nvariable\n(when using libpq or a libpq-based application), or through command-line\nflags\nwhen starting the postgres server. See Chapter 19 for details.\n -- The list of methods is not exhaustive --- perhaps, add \"etc.\", or just\n remove / rephrase these sentences?\n\n----- <in the same section> ------\n\nShow all settings:\n<skip>\n(196 rows)\n -- It's 299 rows as of PostgreSQL 12.4. Perhaps, remove the \"rows\" line?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/sql-truncate.html\n\nWhen RESTART IDENTITY is specified, the implied ALTER SEQUENCE RESTART\noperations are also done transactionally; that is, they will be rolled back\nif\nthe surrounding transaction does not commit. This is unlike the normal\nbehavior\nof ALTER SEQUENCE RESTART.\n -- But ALTER SEQUENCE RESTART is also transactional... what is this about?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/app-pgbasebackup.html\n\nEspecially if the option --checkpoint=fast is not used, this can take some\ntime\nduring which pg_basebackup will be appear to be idle.\n -- \"will be appear to be\" -> \"will appear to be\"?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/pgarchivecleanup.html\n\npg_archivecleanup is designed to work with PostgreSQL 8.0 and later when\nused as\na standalone utility, or with PostgreSQL 9.0 and later when used as an\narchive\ncleanup command.\n -- Isn't this information useless / deprecated by now?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/app-postgres.html\n\nThe -- options will not work on FreeBSD or OpenBSD. Use -c instead. This is\na\nbug in the affected operating systems; a future release of PostgreSQL will\nprovide a workaround if this is not fixed.\n -- This warning appeared here in PostgreSQL 8.2. Is it still relevant?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/view-pg-locks.html\n\n51.74. pg_locks\n\nThe waiting process will sleep until the other lock is released (or a\ndeadlock\nsituation is detected).\n -- There's also lock timeout which seems relevant here.\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/catalog-pg-authid.html\n\nTable 51.8. pg_authid Columns\n -- Some rows in the description have point at the end, some don't\n(seemingly\n at random).\n\n--------------------------------------------------------------------------------\nhttps://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-ASYNC\n\n52.2.6. Asynchronous Operations\n\n(server_encoding, TimeZone, and integer_datetimes were not reported by\nreleases\nbefore 8.0; standard_conforming_strings was not reported by releases before\n8.1;\nIntervalStyle was not reported by releases before 8.4; application_name was\nnot\nreported by releases before 9.0.)\n -- All these versions are unsupported --- perhaps, the sentence could be\n removed?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/protocol-logical-replication.html#PROTOCOL-LOGICAL-MESSAGES-FLOW\n\n52.5.3. Logical Replication Protocol Message Flow\n\nThe origin message indicated that the transaction originated on different\nreplication node.\n -- origin -> Origin (as spelled in the other cases in the paragraph),\n indicated -> indicates?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/error-message-reporting.html\n\nAs of PostgreSQL 9.3, complete coverage exists only for errors in SQLSTATE\nclass 23 (integrity constraint violation), but this is likely to be expanded\nin\nfuture.\n -- Perhaps, this information could be updated?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/nls-translator.html#id-1.10.7.2.6\n\n54.1.4. Editing the PO Files\n\nThere is (unsurprisingly) a PO mode for Emacs, which I find quite useful.\n -- Who is \"I\"? Perhaps, this should be rephrased? Also, why only Emacs is\n mentioned, not any other editors? Perhaps, something like\n \nhttps://www.gnu.org/software/trans-coord/manual/web-trans/html_node/PO-Editors.html\n should be referenced, instead?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/index-functions.html\n\n61.2. Index Access Method Functions\n\nFalse means it is certain that the index entry matches the scan keys. true\nmeans\nthis is not certain, and the conditions represented by the scan keys must be\nrechecked against the heap tuple after fetching it.\n -- \"False\" is capitalized, \"true\" isn't --- this can't be correct?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/gin-implementation.html\n\n66.4. Implementation\n\nAs of PostgreSQL 9.1, null key values can be included in the index.\n -- As 9.1 is already unsupported, perhaps \"As of PostgreSQL 9.1\" could be\n removed?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/gin-implementation.html#GIN-FAST-UPDATE\n\n66.4.1. GIN Fast Update Technique\n\nAs of PostgreSQL 8.4, GIN is capable of postponing much of this work by\ninserting new tuples into a temporary, unsorted list of pending entries.\n -- As 8.4 is already unsupported, perhaps \"As of PostgreSQL 8.4\" could be\n removed?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/gin-tips.html\n\n66.5. GIN Tips and Tricks\n\n Insertion into a GIN index can be slow due to the likelihood of many\nkeys\n being inserted for each item. So, for bulk insertions into a table it is\n advisable to drop the GIN index and recreate it after finishing bulk\n insertion.\n\n As of PostgreSQL 8.4, this advice is less necessary since delayed\nindexing\n is used (see Section 66.4.1 for details). But for very large updates it\nmay\n still be best to drop and recreate the index.\n -- As 8.4 is already unsupported, perhaps it's better to rephrase both\n paragraphs?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/gin-tips.html\n\n66.5. GIN Tips and Tricks\n\ngin_pending_list_limit can be overridden for individual GIN indexes by\nchanging\nstorage parameters, and which allows each GIN index to have its own cleanup\nthreshold.\n -- \"and which allows\" -> \"and it allows\", perhaps?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/row-estimation-examples.html\n\n70.1. Row Estimation Examples\n\nThe outputs shown are taken from version 8.3. The behavior of earlier (or\nlater)\nversions might vary.\n -- 8.3 is very old --- perhaps, it's time to update the chapter?\n\n----- <in the same section> ------\n\nNote also that since ANALYZE uses random sampling while producing\nstatistics,\nthe results will change slightly after any new ANALYZE.\n -- Strictly speaking, it's \"might change\", not \"will change\", as small\ntables\n are scanned in full anyway (which could be relevant here), no?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/errcodes-appendix.html\n\nAppendix A. PostgreSQL Error Codes\n\nAs of PostgreSQL 9.3, complete coverage for this feature exists only for\nerrors\nin SQLSTATE class 23 (integrity constraint violation), but this is likely to\nbe\nexpanded in future.\n -- Perhaps, this information could be updated?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/release-12-3.html\n\nE.2. Release 12.3\n\nThe previous coding could allow the file to be created with permissions that\nwouldn't allow the postmaster to write on it.\n -- Is \"write on\" correct?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/cube.html#id-1.11.7.18.7\n\nF.9.4. Defaults\n\nI believe this union:\n -- \"I\" disagrees with the general style of the documentation?\n\n----- <in the same section> ------\n\nIn all binary operations on differently-dimensioned cubes, I assume the\nlower-dimensional one to be a Cartesian projection, i. e., having zeroes in\nplace of coordinates omitted in the string representation.\n -- \"I\" disagrees with the general style of the documentation?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/isn.html\n\nF.19. isn\n\nIt is hoped that a future version of this module will obtained the prefix\nlist\nfrom one or more tables that can be easily updated by users as needed;\nhowever,\nat present, the list can only be updated by modifying the source code and\nrecompiling.\n -- \"will obtained\" -> \"will obtain\"?\n\n--------------------------------------------------------------------------------\n--\nhttps://www.postgresql.org/docs/current/pgcrypto.html#PGCRYPTO-HASH-SPEED-TABLE\n\n[In the description of the Table F.18. Hash Algorithm Speeds]\n\nThat way I can show the speed with different numbers of iterations.\n -- \"I\" disagrees with the general style of the documentation?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/seg.html#id-1.11.7.43.5\n\nF.34.2. Syntax\n\nBecause ... is widely used in data sources, it is allowed as an alternative\nspelling of ...\n -- While the first of those is <...>, and the second is <..>., it's a\nlittle\n confusing / not very apparent, IMO --- perhaps, the sentence could be\n rephrased so the operator is not at the end of it?\n\n--------------------------------------------------------------------------------\n-- https://www.postgresql.org/docs/current/sepgsql.html#SEPGSQL-INSTALLATION\n\nF.35.2. Installation\n\nBe sure that the libselinux-devel RPM is installed at build time.\n -- Why RPM, specifically (debian(-based) distributions support SELinux,\ntoo)?\n\n\n\n-----\nWBR, Yaroslav Schekin.\n--\nSent from: https://www.postgresql-archive.org/PostgreSQL-hackers-f1928748.html\n\n\n", "msg_date": "Thu, 10 Sep 2020 12:19:55 -0700 (MST)", "msg_from": "Yaroslav <ladayaroslav@yandex.ru>", "msg_from_op": true, "msg_subject": "Probable documentation errors or improvements" }, { "msg_contents": "On Thu, Sep 10, 2020 at 12:20 PM Yaroslav <ladayaroslav@yandex.ru> wrote:\n\n> Disclaimer: I'm not a native speaker, so not sure those are actually\n> incorrect, and can't offer non-trivial suggestions.\n\n\nI skimmed about 2/3rds of these and while I agree on the surface that\nprobably 3/4ths of them are improvements they aren't clear enough wins to\nmethodically go through and write up one or more patches.\n\nThere are a few areas that seem outdated that could use a good once-over in\nthe sgml sources to clean up. For those I'd expect that I or someone else\nmay go and write up actual patches.\n\nThis run-on presentation is off-putting. Even if actual patches are not\nforthcoming I would at least suggest one email per topic with the\nsuggestions broken down into at least bugs (at the top) and\nnon-bugs/improvements.\n\nDavid J.\n\nOn Thu, Sep 10, 2020 at 12:20 PM Yaroslav <ladayaroslav@yandex.ru> wrote:Disclaimer: I'm not a native speaker, so not sure those are actually\nincorrect, and can't offer non-trivial suggestions.I skimmed about 2/3rds of these and while I agree on the surface that probably 3/4ths of them are improvements they aren't clear enough wins to methodically go through and write up one or more patches.There are a few areas that seem outdated that could use a good once-over in the sgml sources to clean up.  For those I'd expect that I or someone else may go and write up actual patches.This run-on presentation is off-putting.  Even if actual patches are not forthcoming I would at least suggest one email per topic with the suggestions broken down into at least bugs (at the top) and non-bugs/improvements.David J.", "msg_date": "Sun, 13 Sep 2020 12:36:26 -0700", "msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Probable documentation errors or improvements" }, { "msg_contents": "On Thu, Sep 10, 2020 at 12:19:55PM -0700, Yaroslav wrote:\n> Disclaimer: I'm not a native speaker, so not sure those are actually\n> incorrect, and can't offer non-trivial suggestions.\n\nhttps://www.postgresql.org/message-id/flat/CAKFQuwZh3k_CX2-%2BNcZ%3DFZss4bX6ASxDFEXJTY6u4wTH%2BG8%2BKA%40mail.gmail.com#9f9eba0cbbf9b57455503537575f5339\n\nMost of these appear to be reasonable corrections or improvements.\n\nWould you want to submit a patch against the master branch ?\nIt'll be easier for people to read when it's in a consistent format.\nAnd less work to read it than to write it.\n\nI suggest to first handle the 10+ changes which are most important and in need\nof fixing. After a couple rounds, then see if what's left is worth patching.\n\n-- \nJustin\n\n\n", "msg_date": "Sat, 19 Sep 2020 12:55:59 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Probable documentation errors or improvements" }, { "msg_contents": "On Sat, Sep 19, 2020 at 12:55:58PM -0500, Justin Pryzby wrote:\n> On Thu, Sep 10, 2020 at 12:19:55PM -0700, Yaroslav wrote:\n> > Disclaimer: I'm not a native speaker, so not sure those are actually\n> > incorrect, and can't offer non-trivial suggestions.\n> \n> https://www.postgresql.org/message-id/flat/CAKFQuwZh3k_CX2-%2BNcZ%3DFZss4bX6ASxDFEXJTY6u4wTH%2BG8%2BKA%40mail.gmail.com#9f9eba0cbbf9b57455503537575f5339\n> \n> Most of these appear to be reasonable corrections or improvements.\n> \n> Would you want to submit a patch against the master branch ?\n> It'll be easier for people to read when it's in a consistent format.\n> And less work to read it than to write it.\n> \n> I suggest to first handle the 10+ changes which are most important and in need\n> of fixing. After a couple rounds, then see if what's left is worth patching.\n\nA couple of these were already fixed (querytree and \"be appear\").\n\nI provide a patch for a few others.\n\nCopying Teodor et al regarding tsquery.\n\nwdiff to follow.\n\ncommit 6c5a4e6fde2841f6a2ad00f3cc4530e7fcf9a9f3\nAuthor: Justin Pryzby <pryzbyj@telsasoft.com>\nDate: Tue Sep 22 23:34:54 2020 -0500\n\n fix tsquery example\n \n broken since bb140506df605fab58f48926ee1db1f80bdafb59\n\ndiff --git a/doc/src/sgml/textsearch.sgml b/doc/src/sgml/textsearch.sgml\nindex 8af6ac01d3..7daf292468 100644\n--- a/doc/src/sgml/textsearch.sgml\n+++ b/doc/src/sgml/textsearch.sgml\n@@ -1623,9 +1623,9 @@ occurrences to display in the result.',\n\n<screen>\nSELECT to_tsquery('fat') &lt;-&gt; to_tsquery('cat | rat');\n ?column?\n[-------------------------------------]{+----------------------------+}\n 'fat' &lt;-&gt; {+(+} 'cat' |[-'fat' &lt;-&gt;-] 'rat' {+)+}\n</screen>\n </para>\n </listitem>\n\ncommit 096a9097d58de8e2d21e42fab528b27a5213a699\nAuthor: Justin Pryzby <pryzbyj@telsasoft.com>\nDate: Tue Sep 22 23:13:00 2020 -0500\n\n HAVING conditions cannot be repeated\n\ndiff --git a/doc/src/sgml/ref/select.sgml b/doc/src/sgml/ref/select.sgml\nindex b93e4ca208..94889b66b4 100644\n--- a/doc/src/sgml/ref/select.sgml\n+++ b/doc/src/sgml/ref/select.sgml\n@@ -38,7 +38,7 @@ SELECT [ ALL | DISTINCT [ ON ( <replaceable class=\"parameter\">expression</replac\n [ FROM <replaceable class=\"parameter\">from_item</replaceable> [, ...] ]\n [ WHERE <replaceable class=\"parameter\">condition</replaceable> ]\n [ GROUP BY <replaceable class=\"parameter\">grouping_element</replaceable> [, ...] ]\n [ HAVING <replaceable class=\"parameter\">condition</replaceable>[-[, ...]-] ]\n [ WINDOW <replaceable class=\"parameter\">window_name</replaceable> AS ( <replaceable class=\"parameter\">window_definition</replaceable> ) [, ...] ]\n [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] <replaceable class=\"parameter\">select</replaceable> ]\n [ ORDER BY <replaceable class=\"parameter\">expression</replaceable> [ ASC | DESC | USING <replaceable class=\"parameter\">operator</replaceable> ] [ NULLS { FIRST | LAST } ] [, ...] ]\ndiff --git a/doc/src/sgml/ref/select_into.sgml b/doc/src/sgml/ref/select_into.sgml\nindex b1af52a4da..e82e416d60 100644\n--- a/doc/src/sgml/ref/select_into.sgml\n+++ b/doc/src/sgml/ref/select_into.sgml\n@@ -28,7 +28,7 @@ SELECT [ ALL | DISTINCT [ ON ( <replaceable class=\"parameter\">expression</replac\n [ FROM <replaceable class=\"parameter\">from_item</replaceable> [, ...] ]\n [ WHERE <replaceable class=\"parameter\">condition</replaceable> ]\n [ GROUP BY <replaceable class=\"parameter\">expression</replaceable> [, ...] ]\n [ HAVING <replaceable class=\"parameter\">condition</replaceable>[-[, ...]-] ]\n [ WINDOW <replaceable class=\"parameter\">window_name</replaceable> AS ( <replaceable class=\"parameter\">window_definition</replaceable> ) [, ...] ]\n [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] <replaceable class=\"parameter\">select</replaceable> ]\n [ ORDER BY <replaceable class=\"parameter\">expression</replaceable> [ ASC | DESC | USING <replaceable class=\"parameter\">operator</replaceable> ] [ NULLS { FIRST | LAST } ] [, ...] ]\n\ncommit 1e16102f906d9ead33ebdfc0b6f5d862e851131b\nAuthor: Justin Pryzby <pryzbyj@telsasoft.com>\nDate: Tue Sep 22 22:24:14 2020 -0500\n\n style and consistency\n\ndiff --git a/doc/src/sgml/indexam.sgml b/doc/src/sgml/indexam.sgml\nindex 390c49eb6a..649020b7da 100644\n--- a/doc/src/sgml/indexam.sgml\n+++ b/doc/src/sgml/indexam.sgml\n@@ -612,7 +612,7 @@ amgettuple (IndexScanDesc scan,\n will pass the caller's snapshot test. On success, <function>amgettuple</function>\n must also set <literal>scan-&gt;xs_recheck</literal> to true or false.\n False means it is certain that the index entry matches the scan keys.\n [-true-]{+True+} means this is not certain, and the conditions represented by the\n scan keys must be rechecked against the heap tuple after fetching it.\n This provision supports <quote>lossy</quote> index operators.\n Note that rechecking will extend only to the scan conditions; a partial\n\ncommit 44c7efab0499644060c19868d4c431007e8cccaa\nAuthor: Justin Pryzby <pryzbyj@telsasoft.com>\nDate: Tue Sep 22 22:55:59 2020 -0500\n\n distro agnostic\n\ndiff --git a/doc/src/sgml/sepgsql.sgml b/doc/src/sgml/sepgsql.sgml\nindex 9961569afc..15417bf19d 100644\n--- a/doc/src/sgml/sepgsql.sgml\n+++ b/doc/src/sgml/sepgsql.sgml\n@@ -88,7 +88,7 @@ Policy from config file: targeted\n <para>\n To build this module, include the option <literal>--with-selinux</literal> in\n your PostgreSQL <literal>configure</literal> command. Be sure that the\n <filename>libselinux-devel</filename> [-RPM-]{+package+} is installed at build time.\n </para>\n\n <para>\n@@ -177,7 +177,7 @@ $ for DBNAME in template0 template1 postgres; do\n Makefile on your system; the path shown below is only an example.\n (This Makefile is usually supplied by the\n <filename>selinux-policy-devel</filename> or\n <filename>selinux-policy</filename> [-RPM.)-]{+package.)+}\n Once built, install this policy package using the\n <command>semodule</command> command, which loads supplied policy packages\n into the kernel. If the package is correctly installed,\n\ncommit 1584c0dd6a5183b915811c89af08f135479509ab\nAuthor: Justin Pryzby <pryzbyj@telsasoft.com>\nDate: Tue Sep 22 22:55:48 2020 -0500\n\n grammar\n\ndiff --git a/doc/src/sgml/gin.sgml b/doc/src/sgml/gin.sgml\nindex 5c8d4d5275..67754f52f6 100644\n--- a/doc/src/sgml/gin.sgml\n+++ b/doc/src/sgml/gin.sgml\n@@ -612,7 +612,7 @@\n </para>\n <para>\n <varname>gin_pending_list_limit</varname> can be overridden for individual\n GIN indexes by changing storage parameters,[-and-] which allows each\n GIN index to have its own cleanup threshold.\n For example, it's possible to increase the threshold only for the GIN\n index which can be updated heavily, and decrease it otherwise.\ndiff --git a/doc/src/sgml/high-availability.sgml b/doc/src/sgml/high-availability.sgml\nindex beb309e668..a9b7e8fc99 100644\n--- a/doc/src/sgml/high-availability.sgml\n+++ b/doc/src/sgml/high-availability.sgml\n@@ -1503,7 +1503,7 @@ synchronous_standby_names = 'ANY 2 (s1, s2, s3)'\n Note that in this mode, the server will apply WAL one file at a\n time, so if you use the standby server for queries (see Hot Standby),\n there is a delay between an action in the primary and when the\n action becomes visible in the standby, corresponding {+to+} the time it takes\n to fill up the WAL file. <varname>archive_timeout</varname> can be used to make that delay\n shorter. Also note that you can't combine streaming replication with\n this method.\ndiff --git a/doc/src/sgml/isn.sgml b/doc/src/sgml/isn.sgml\nindex e55ed07312..709bc8345c 100644\n--- a/doc/src/sgml/isn.sgml\n+++ b/doc/src/sgml/isn.sgml\n@@ -14,7 +14,7 @@\n hard-coded list of prefixes; this list of prefixes is also used to hyphenate\n numbers on output. Since new prefixes are assigned from time to time, the\n list of prefixes may be out of date. It is hoped that a future version of\n this module will [-obtained-]{+obtain+} the prefix list from one or more tables that\n can be easily updated by users as needed; however, at present, the\n list can only be updated by modifying the source code and recompiling.\n Alternatively, prefix validation and hyphenation support may be\ndiff --git a/doc/src/sgml/mvcc.sgml b/doc/src/sgml/mvcc.sgml\nindex 6920913a26..92861e5cfd 100644\n--- a/doc/src/sgml/mvcc.sgml\n+++ b/doc/src/sgml/mvcc.sgml\n@@ -1246,7 +1246,7 @@ ERROR: could not serialize access due to read/write dependencies among transact\n <para>\n The <literal>FOR UPDATE</literal> lock mode\n is also acquired by any <command>DELETE</command> on a row, and also by an\n <command>UPDATE</command> that modifies the values [-on-]{+of+} certain columns. Currently,\n the set of columns considered for the <command>UPDATE</command> case are those that\n have a unique index on them that can be used in a foreign key (so partial\n indexes and expressional indexes are not considered), but this may change\ndiff --git a/doc/src/sgml/protocol.sgml b/doc/src/sgml/protocol.sgml\nindex f5e3318106..06068f87a4 100644\n--- a/doc/src/sgml/protocol.sgml\n+++ b/doc/src/sgml/protocol.sgml\n@@ -2837,7 +2837,7 @@ The commands accepted in replication mode are:\n <para>\n Every sent transaction contains zero or more DML messages (Insert,\n Update, Delete). In case of a cascaded setup it can also contain Origin\n messages. The origin message [-indicated-]{+indicates+} that the transaction originated on\n different replication node. Since a replication node in the scope of logical\n replication protocol can be pretty much anything, the only identifier\n is the origin name. It's downstream's responsibility to handle this as\ndiff --git a/doc/src/sgml/textsearch.sgml b/doc/src/sgml/textsearch.sgml\nindex 2ebdf02bfa..8af6ac01d3 100644\n--- a/doc/src/sgml/textsearch.sgml\n+++ b/doc/src/sgml/textsearch.sgml\n@@ -1645,7 +1645,7 @@ SELECT to_tsquery('fat') &lt;-&gt; to_tsquery('cat | rat');\n <listitem>\n <para>\n Returns a query that searches for a match to the first given query\n followed by a match to the second given query at a distance of [-at-]{+exactly+}\n <replaceable>distance</replaceable> lexemes, using\n the <literal>&lt;<replaceable>N</replaceable>&gt;</literal>\n <type>tsquery</type> operator. For example:\n\ncommit fe18f111c589378eb6bc0ed0ac6f8efb317c25b4\nAuthor: Justin Pryzby <pryzbyj@telsasoft.com>\nDate: Tue Sep 22 22:48:52 2020 -0500\n\n Avoid ending a sentence about \"...\" with \"..\" ..\n \n .. which then looks just the same as \"...\".\n\ndiff --git a/doc/src/sgml/seg.sgml b/doc/src/sgml/seg.sgml\nindex e86142d885..e0dfbc76cf 100644\n--- a/doc/src/sgml/seg.sgml\n+++ b/doc/src/sgml/seg.sgml\n@@ -205,8 +205,8 @@ test=&gt; select '6.25 .. 6.50'::seg as \"pH\";\n </table>\n\n <para>\n Because {+the+} <literal>...</literal> {+operator+} is widely used in data sources, it is allowed\n as an alternative spelling of [-<literal>..</literal>.-]{+the <literal>..</literal> operator.+} Unfortunately, this\n creates a parsing ambiguity: it is not clear whether the upper bound\n in <literal>0...23</literal> is meant to be <literal>23</literal> or <literal>0.23</literal>.\n This is resolved by requiring at least one digit before the decimal\n\ncommit fabaf97865d46377ed4dbbbb1109299eb037394f\nAuthor: Justin Pryzby <pryzbyj@telsasoft.com>\nDate: Tue Sep 22 22:51:47 2020 -0500\n\n punctuation\n\ndiff --git a/doc/src/sgml/catalogs.sgml b/doc/src/sgml/catalogs.sgml\nindex de9bacd34f..d1b8fc8010 100644\n--- a/doc/src/sgml/catalogs.sgml\n+++ b/doc/src/sgml/catalogs.sgml\n@@ -1525,7 +1525,7 @@\n </para>\n <para>\n Role can log in. That is, this role can be given as the initial\n session authorization [-identifier-]{+identifier.+}\n </para></entry>\n </row>\n\ndiff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml\nindex 8eabf93834..1c753ccb7e 100644\n--- a/doc/src/sgml/config.sgml\n+++ b/doc/src/sgml/config.sgml\n@@ -10084,8 +10084,8 @@ LOG: CleanUpLock: deleting: lock(0xb7acd844) id(24688,24696,0,0,0,1)\n </term>\n <listitem>\n <para>\n If set, do not trace locks for tables below this [-OID. (use-]{+OID (used+} to avoid\n output on system [-tables)-]{+tables).+}\n </para>\n <para>\n This parameter is only available if the <symbol>LOCK_DEBUG</symbol>\ndiff --git a/doc/src/sgml/func.sgml b/doc/src/sgml/func.sgml\nindex 461b748d89..8ec58c8577 100644\n--- a/doc/src/sgml/func.sgml\n+++ b/doc/src/sgml/func.sgml\n@@ -26656,7 +26656,7 @@ BEGIN\n RAISE NOTICE 'rewriting table % for reason %',\n pg_event_trigger_table_rewrite_oid()::regclass,\n pg_event_trigger_table_rewrite_reason();\n[-END;-]{+END+}\n$$;\n\nCREATE EVENT TRIGGER test_table_rewrite_oid\ndiff --git a/doc/src/sgml/parallel.sgml b/doc/src/sgml/parallel.sgml\nindex e31bd9d3ce..c81abff48d 100644\n--- a/doc/src/sgml/parallel.sgml\n+++ b/doc/src/sgml/parallel.sgml\n@@ -471,7 +471,7 @@ EXPLAIN SELECT * FROM pgbench_accounts WHERE filler LIKE '%x%';\n </para>\n\n <para>\n The following operations are always parallel [-restricted.-]{+restricted:+}\n </para>\n\n <itemizedlist>\n\ncommit adf050ac6cc7d0905fc1613dce1a04f76a892609\nAuthor: Justin Pryzby <pryzbyj@telsasoft.com>\nDate: Tue Sep 22 21:40:17 2020 -0500\n\n extraneous comma\n\ndiff --git a/doc/src/sgml/rules.sgml b/doc/src/sgml/rules.sgml\nindex bcf860b68b..d6e3463ac2 100644\n--- a/doc/src/sgml/rules.sgml\n+++ b/doc/src/sgml/rules.sgml\n@@ -769,7 +769,7 @@ SELECT t1.a, t2.b, t1.ctid FROM t1, t2 WHERE t1.a = t2.a;\n</para>\n\n<para>\n The benefit of implementing views with the rule system [-is,-]{+is+}\n that the planner has all\n the information about which tables have to be scanned plus the\n relationships between these tables plus the restrictive\n@@ -781,7 +781,7 @@ SELECT t1.a, t2.b, t1.ctid FROM t1, t2 WHERE t1.a = t2.a;\n the best path to execute the query, and the more information\n the planner has, the better this decision can be. And\n the rule system as implemented in <productname>PostgreSQL</productname>\n [-ensures,-]{+ensures+} that this is all information available about the query\n up to that point.\n</para>\n</sect2>", "msg_date": "Wed, 23 Sep 2020 09:58:39 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Probable documentation errors or improvements" }, { "msg_contents": "Split one patch about text search, added another one (sequences), added some\ninfo to commit messages, and added here.\nhttps://commitfest.postgresql.org/30/2744/\n\n-- \nJustin", "msg_date": "Fri, 25 Sep 2020 09:30:00 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Probable documentation errors or improvements" }, { "msg_contents": "On Fri, Sep 25, 2020 at 09:30:00AM -0500, Justin Pryzby wrote:\n> Split one patch about text search, added another one (sequences), added some\n> info to commit messages, and added here.\n> https://commitfest.postgresql.org/30/2744/\n\nAdded an additional patch regarding spaces between function arguments.\n\n-- \nJustin", "msg_date": "Mon, 5 Oct 2020 14:19:22 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Probable documentation errors or improvements" }, { "msg_contents": "On 05/10/2020 22:19, Justin Pryzby wrote:\n> On Fri, Sep 25, 2020 at 09:30:00AM -0500, Justin Pryzby wrote:\n>> Split one patch about text search, added another one (sequences), added some\n>> info to commit messages, and added here.\n>> https://commitfest.postgresql.org/30/2744/\n> \n> Added an additional patch regarding spaces between function arguments.\n\nPushed most of these.\n\nI left out these changes in sepgsql docs:\n\n> --- a/doc/src/sgml/sepgsql.sgml\n> +++ b/doc/src/sgml/sepgsql.sgml\n> @@ -88,7 +88,7 @@ Policy from config file: targeted\n> <para>\n> To build this module, include the option <literal>--with-selinux</literal> in\n> your PostgreSQL <literal>configure</literal> command. Be sure that the\n> - <filename>libselinux-devel</filename> RPM is installed at build time.\n> + <filename>libselinux-devel</filename> package is installed at build time.\n> </para>\n\nIt's true that the sentence is unusually distro-specific, but I think \nsecond instance of this becomes ambiguous if we just change RPM to package:\n\n> <para>\n> Second, build and install the policy package for the regression test.\n> The <filename>sepgsql-regtest</filename> policy is a special purpose policy package\n> which provides a set of rules to be allowed during the regression tests.\n> It should be built from the policy source file\n> <filename>sepgsql-regtest.te</filename>, which is done using\n> <command>make</command> with a Makefile supplied by SELinux.\n> You will need to locate the appropriate\n> Makefile on your system; the path shown below is only an example.\n> (This Makefile is usually supplied by the\n> <filename>selinux-policy-devel</filename> or\n> <filename>selinux-policy</filename> RPM.)\n> Once built, install this policy package using the\n> <command>semodule</command> command, which loads supplied policy packages\n> into the kernel. If the package is correctly installed,\n> <literal><command>semodule</command> -l</literal> should list <literal>sepgsql-regtest</literal> as an\n> available policy package:\n> </para>\n\nThe paragraph talks about \"policy package\", so using just \"package\" to \nrefer to a .rpm/.deb file would be confusing. Suggestions are welcome.\n\n- Heikki\n\n\n", "msg_date": "Mon, 19 Oct 2020 19:36:29 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Probable documentation errors or improvements" }, { "msg_contents": "On Mon, Oct 19, 2020 at 07:36:29PM +0300, Heikki Linnakangas wrote:\n> On 05/10/2020 22:19, Justin Pryzby wrote:\n> > On Fri, Sep 25, 2020 at 09:30:00AM -0500, Justin Pryzby wrote:\n> > > Split one patch about text search, added another one (sequences), added some\n> > > info to commit messages, and added here.\n> > > https://commitfest.postgresql.org/30/2744/\n> > \n> > Added an additional patch regarding spaces between function arguments.\n> \n> Pushed most of these.\n\nThanks. \n\nYaroslav, could you prepare a patch for your remaining suggestions ?\nI suggest to include just the handful of items which are most important (most\nwrong/ambiguous/confusing).\n\n-- \nJustin\n\n\n", "msg_date": "Mon, 19 Oct 2020 11:45:29 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Probable documentation errors or improvements" }, { "msg_contents": "Heikki Linnakangas <hlinnaka@iki.fi> writes:\n> I left out these changes in sepgsql docs:\n\n>> --- a/doc/src/sgml/sepgsql.sgml\n>> +++ b/doc/src/sgml/sepgsql.sgml\n>> @@ -88,7 +88,7 @@ Policy from config file: targeted\n>> <para>\n>> To build this module, include the option <literal>--with-selinux</literal> in\n>> your PostgreSQL <literal>configure</literal> command. Be sure that the\n>> - <filename>libselinux-devel</filename> RPM is installed at build time.\n>> + <filename>libselinux-devel</filename> package is installed at build time.\n>> </para>\n\n> It's true that the sentence is unusually distro-specific, but I think \n> second instance of this becomes ambiguous if we just change RPM to package:\n\nThere's also the fact that the package name \"libselinux-devel\" is itself\nRed Hat specific --- Debian-based distros would call it something else,\neven assuming that they have an exact equivalent which they might not.\nThe other advice you mention is also pretty RH-specific.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 19 Oct 2020 14:37:02 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Probable documentation errors or improvements" }, { "msg_contents": "Thank you for preparing the patches, and Heikki Linnakangas for pushing those!Yaroslav, could you prepare a patch for your remaining suggestions ?I suggest to include just the handful of items which are most important (mostwrong/ambiguous/confusing).Let me write this again: I'm not a native speaker, so not sure those are actually incorrect, and can't offer non-trivial suggestions. Anyway, I've tried to remove the already fixed things (also by other patches mentioned in the thread) from my initial list, and attach it. Also, I've looked over the pushed patches, and spotted these: -- https://www.postgresql.org/docs/current/catalog-pg-authid.html Table 51.8. pg_authid Columns-- Some rows in the description have point at the end, some don't (seemingly at random). The applied patch fixed only one of those cases... also seemingly at random. Would be nice if someone read the whole table and made a decision about how it should be. If (just guessing here) the rule is \"there should be no point if it's just one sentence\", then \"Role bypasses every row level security policy, see Section 5.8 for more information.\" is still wrong. Then, while \";\" after \"END\" were added in doc/src/sgml/plpgsql.sgml, but in doc/src/sgml/func.sgml they still were not. Finally, while the patches fix a lot of whitespace in function arguments, the original complaint about div() and mod() is still not fixed. -- WBR, Yaroslav Schekin.", "msg_date": "Fri, 20 Nov 2020 20:51:12 +0300", "msg_from": "=?utf-8?B?0KnQtdC60LjQvSDQr9GA0L7RgdC70LDQsg==?=\n <ladayaroslav@yandex.ru>", "msg_from_op": false, "msg_subject": "Re: Probable documentation errors or improvements" } ]
[ { "msg_contents": "Hi\n\nTake the following cluster with:\n - node1 (initial primary)\n - node2 (standby)\n - node3 (standby)\n\nFollowing activity takes place (greatly simplified from a real-world situation):\n\n1. node1 is shut down.\n2. node3 is promoted\n3. node2 is attached to node3.\n4. node1 is attached to node3\n5. node1 is then promoted (creating a split brain situation with\n node1 and node3 as primaries)\n6. node2 and node3 are shut down (in that order).\n7. pg_rewind is executed to reset node2 so it can reattach\n to node1 as a standby. pg_rewind claims:\n\n pg_rewind: servers diverged at WAL location X/XXXXXXX on timeline 2\n pg_rewind: no rewind required\n\n8. based off that assurance, node2 is restarted with replication configuration\n pointing to node1 - but it is unable to attach, with node2's log reporting\n something like:\n\n new timeline 3 forked off current database system timeline 2\nbefore current recovery point X/XXXXXXX\n\nThe cause is that pg_rewind is assuming that if the node's last\ncheckpoint matches the\ndivergence point, no rewind is needed:\n\n if (chkptendrec == divergerec)\n rewind_needed = false;\n\nbut in this case there *are* records beyond the last checkpoint, which can be\ninferred from \"minRecoveryPoint\" - but this is not checked.\n\nAttached patch addresses this. It includes a test, which doesn't make use of\nthe RewindTest module, as that hard-codes a primary and a standby, while here\nthree nodes are needed (I can't come up with a situation where this can be\nreproduced with only two nodes). The test sets \"wal_keep_size\" so would need\nmodification for Pg12 and earlier.\n\nRegards\n\nIan Barwick\n\n-- \n Ian Barwick https://www.2ndQuadrant.com/\n PostgreSQL Development, 24x7 Support, Training & Services", "msg_date": "Fri, 11 Sep 2020 15:42:34 +0900", "msg_from": "Ian Barwick <ian.barwick@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Corner-case bug in pg_rewind" }, { "msg_contents": "On 11/09/2020 09:42, Ian Barwick wrote:\n> Take the following cluster with:\n> - node1 (initial primary)\n> - node2 (standby)\n> - node3 (standby)\n> \n> Following activity takes place (greatly simplified from a real-world situation):\n> \n> 1. node1 is shut down.\n> 2. node3 is promoted\n> 3. node2 is attached to node3.\n> 4. node1 is attached to node3\n> 5. node1 is then promoted (creating a split brain situation with\n> node1 and node3 as primaries)\n> 6. node2 and node3 are shut down (in that order).\n> 7. pg_rewind is executed to reset node2 so it can reattach\n> to node1 as a standby. pg_rewind claims:\n> \n> pg_rewind: servers diverged at WAL location X/XXXXXXX on timeline 2\n> pg_rewind: no rewind required\n> \n> 8. based off that assurance, node2 is restarted with replication configuration\n> pointing to node1 - but it is unable to attach, with node2's log reporting\n> something like:\n> \n> new timeline 3 forked off current database system timeline 2\n> before current recovery point X/XXXXXXX\n> \n> The cause is that pg_rewind is assuming that if the node's last\n> checkpoint matches the\n> divergence point, no rewind is needed:\n> \n> if (chkptendrec == divergerec)\n> rewind_needed = false;\n> \n> but in this case there *are* records beyond the last checkpoint, which can be\n> inferred from \"minRecoveryPoint\" - but this is not checked.\n\nYep, I think you're right.\n\n> Attached patch addresses this. It includes a test, which doesn't make use of\n> the RewindTest module, as that hard-codes a primary and a standby, while here\n> three nodes are needed (I can't come up with a situation where this can be\n> reproduced with only two nodes). The test sets \"wal_keep_size\" so would need\n> modification for Pg12 and earlier.\n\nI think we also need to change the extractPageMap() call:\n\n> \t/*\n> \t * Read the target WAL from last checkpoint before the point of fork, to\n> \t * extract all the pages that were modified on the target cluster after\n> \t * the fork. We can stop reading after reaching the final shutdown record.\n> \t * XXX: If we supported rewinding a server that was not shut down cleanly,\n> \t * we would need to replay until the end of WAL here.\n> \t */\n> \tif (showprogress)\n> \t\tpg_log_info(\"reading WAL in target\");\n> \textractPageMap(datadir_target, chkptrec, lastcommontliIndex,\n> \t\t\t\t ControlFile_target.checkPoint, restore_command);\n> \tfilemap_finalize();\n\nso that it scans all the way up to minRecoveryPoint, instead of stopping \nat ControlFile_target.checkPoint. Otherwise, we will fail to rewind \nchanges that happened after the last checkpoint. And we need to do that \nregardless of the \"no rewind required\" bug, any time we rewind a server \nthat's in DB_SHUTDOWNED_IN_RECOVERY state. I'm surprised none of the \nexisting tests have caught that. Am I missing something?\n\n- Heikki\n\n\n", "msg_date": "Tue, 29 Sep 2020 15:00:13 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Corner-case bug in pg_rewind" }, { "msg_contents": "I did some effort to review your patch which seems legit to me.\nI think some minor things are better to be improved i.e.\n\n1. Comment regarding\n------\n347 * Check for the possibility that the target is in fact a direct\n348 * ancestor of the source. In that case, there is no divergent\nhistory\n349 * in the target that needs rewinding.\n------\nare better be reformulated as overall block contents are mostly cover vice\nversa case of a target NOT being a direct ancestor of the source. Maybe:\n\"We need rewind in cases when .... and don't need only if the target is a\ndirect ancestor of the source.\" I think it will be more understandable if\nit would be a commentary with descriptions of all cases in the block or no\ncommentary before the block at all with commentaries of these cases on each\nif/else inside the block instead.\n\n2. When I do the test with no patching of pg_rewind.c I get the output:\n-----\n# Failed test 'pg_rewind detects rewind needed stderr /(?^:rewinding from\nlast common checkpoint at)/'\n# at t/007_min_recovery_point.pl line 107.\n# 'pg_rewind: servers diverged at WAL location 0/3000180\non timeline 2\n# pg_rewind: no rewind required\n# '\n# doesn't match '(?^:rewinding from last common checkpoint at)'\n# Looks like you failed 1 test of 2.\nt/007_min_recovery_point.pl .. Dubious, test returned 1 (wstat 256, 0x100)\nFailed 1/2 subtests\n\nTest Summary Report\n-------------------\nt/007_min_recovery_point.pl (Wstat: 256 Tests: 2 Failed: 1)\n Failed test: 2\n Non-zero exit status: 1\n-------\nMaybe it can just give \"failed\" without so many details?\n\nAlso, I think Heikki's notion could be fulfilled.\n\nApart from this I consider the patch clean, clear, tests are passes and I'd\nrecommend it to commit after a minor improvement described.\nThank you!\n\n-- \nBest regards,\nPavel Borisov\n\nPostgres Professional: http://postgrespro.com <http://www.postgrespro.com>\n\nI did some effort to review your patch which seems legit to me.I think some minor things are better to be improved i.e. 1. Comment regarding ------347          * Check for the possibility that the target is in fact a direct348          * ancestor of the source. In that case, there is no divergent history349          * in the target that needs rewinding.------are better be reformulated as overall block contents are mostly cover vice versa case of a target NOT being a direct ancestor of the source. Maybe: \"We need rewind in cases when .... and don't need only if the target is a direct ancestor of the source.\" I think it will be more understandable if it would be a commentary with descriptions of all cases in the block or no commentary before the block at all with commentaries of these cases on each if/else inside the block instead.2. When I do the test with no patching of pg_rewind.c I get the output:-----#   Failed test 'pg_rewind detects rewind needed stderr /(?^:rewinding from last common checkpoint at)/'#   at t/007_min_recovery_point.pl line 107.#                   'pg_rewind: servers diverged at WAL location 0/3000180 on timeline 2# pg_rewind: no rewind required# '#     doesn't match '(?^:rewinding from last common checkpoint at)'# Looks like you failed 1 test of 2.t/007_min_recovery_point.pl .. Dubious, test returned 1 (wstat 256, 0x100)Failed 1/2 subtestsTest Summary Report-------------------t/007_min_recovery_point.pl (Wstat: 256 Tests: 2 Failed: 1)  Failed test:  2  Non-zero exit status: 1-------Maybe it can just give \"failed\" without so many details?Also, I think Heikki's notion could be fulfilled.Apart from this I consider the patch clean, clear, tests are passes and I'd recommend it to commit after a minor improvement described.Thank you!-- Best regards,Pavel BorisovPostgres Professional: http://postgrespro.com", "msg_date": "Tue, 10 Nov 2020 13:06:46 +0400", "msg_from": "Pavel Borisov <pashkin.elfe@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Corner-case bug in pg_rewind" }, { "msg_contents": "2020年11月10日(火) 18:07 Pavel Borisov <pashkin.elfe@gmail.com>:\n>\n> I did some effort to review your patch which seems legit to me.\n\nThanks for the review and feedback.\n\n> I think some minor things are better to be improved i.e.\n>\n> 1. Comment regarding\n> ------\n> 347 * Check for the possibility that the target is in fact a direct\n> 348 * ancestor of the source. In that case, there is no divergent history\n> 349 * in the target that needs rewinding.\n> ------\n> are better be reformulated as overall block contents are mostly cover vice\n> versa case of a target NOT being a direct ancestor of the source. Maybe: \"We\n> need rewind in cases when .... and don't need only if the target is a direct\n> ancestor of the source.\" I think it will be more understandable if it would be\n> a commentary with descriptions of all cases in the block or no commentary\n> before the block at all with commentaries of these cases on each if/else\n> inside the block instead.\n\nThe comment you cite is not part of this patch. I suspect there might be some\nscope for improving the comments in general, but that would need to be done\nseperately.\n\n> 2. When I do the test with no patching of pg_rewind.c I get the output:\n> -----\n> # Failed test 'pg_rewind detects rewind needed stderr /(?^:rewinding from last common checkpoint at)/'\n> # at t/007_min_recovery_point.pl line 107.\n> # 'pg_rewind: servers diverged at WAL location 0/3000180 on timeline 2\n> # pg_rewind: no rewind required\n> # '\n> # doesn't match '(?^:rewinding from last common checkpoint at)'\n> # Looks like you failed 1 test of 2.\n> t/007_min_recovery_point.pl .. Dubious, test returned 1 (wstat 256, 0x100)\n> Failed 1/2 subtests\n>\n> Test Summary Report\n> -------------------\n> t/007_min_recovery_point.pl (Wstat: 256 Tests: 2 Failed: 1)\n> Failed test: 2\n> Non-zero exit status: 1\n> -------\n> Maybe it can just give \"failed\" without so many details?\n\nThat's just the way the tests work - an individual test has no influence\nover that output.\n\n> Also, I think Heikki's notion could be fulfilled.\n\nI spent a bit of time looking at that suggestion but couldn't actually\nverify it was an issue which needed fixing.\n\nNote that the patch may require reworking for HEAD due to changes in\ncommit 9c4f5192f6. I'll try to take another look this week.\n\n\nRegards\n\nIan Barwick\n\n\n--\nEnterpriseDB: https://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 16 Nov 2020 11:49:49 +0900", "msg_from": "Ian Lawrence Barwick <barwick@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Corner-case bug in pg_rewind" }, { "msg_contents": ">\n> > 1. Comment regarding\n> > ------\n> > 347 * Check for the possibility that the target is in fact a\n> direct\n> > 348 * ancestor of the source. In that case, there is no\n> divergent history\n> > 349 * in the target that needs rewinding.\n> > ------\n> > are better be reformulated as overall block contents are mostly cover\n> vice\n> > versa case of a target NOT being a direct ancestor of the source. Maybe:\n> \"We\n> > need rewind in cases when .... and don't need only if the target is a\n> direct\n> > ancestor of the source.\" I think it will be more understandable if it\n> would be\n> > a commentary with descriptions of all cases in the block or no commentary\n> > before the block at all with commentaries of these cases on each if/else\n> > inside the block instead.\n>\n> The comment you cite is not part of this patch. I suspect there might be\n> some\n>\nSure, it is comment describes the whole block the patch introduces changes\ninto. If it could be rendered more relevant and anyway you are planning to\nrevise it again, it would be great to change it also. But I don't insist.\n\n\n> Note that the patch may require reworking for HEAD due to changes in\n> commit 9c4f5192f6. I'll try to take another look this week.\n>\nThank you!\n\n-- \nBest regards,\nPavel Borisov\n\nPostgres Professional: http://postgrespro.com <http://www.postgrespro.com>\n\n> 1. Comment regarding\n> ------\n> 347          * Check for the possibility that the target is in fact a direct\n> 348          * ancestor of the source. In that case, there is no divergent history\n> 349          * in the target that needs rewinding.\n> ------\n> are better be reformulated as overall block contents are mostly cover vice\n> versa case of a target NOT being a direct ancestor of the source. Maybe: \"We\n> need rewind in cases when .... and don't need only if the target is a direct\n> ancestor of the source.\" I think it will be more understandable if it would be\n> a commentary with descriptions of all cases in the block or no commentary\n> before the block at all with commentaries of these cases on each if/else\n>  inside the block instead.\n\nThe comment you cite is not part of this patch. I suspect there might be someSure, it is comment describes the whole block the patch introduces changes into. If it could be rendered more relevant and anyway you are planning to revise it again, it would be great to change it also. But I don't insist.    \nNote that the patch  may require reworking for HEAD due to changes in\ncommit 9c4f5192f6. I'll try to take another look this week.Thank you!-- Best regards,Pavel BorisovPostgres Professional: http://postgrespro.com", "msg_date": "Mon, 16 Nov 2020 10:58:20 +0400", "msg_from": "Pavel Borisov <pashkin.elfe@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Corner-case bug in pg_rewind" }, { "msg_contents": "On 16.11.2020 05:49, Ian Lawrence Barwick wrote:\n>\n> Note that the patch may require reworking for HEAD due to changes in\n> commit 9c4f5192f6. I'll try to take another look this week.\n>\n>\n> Regards\n>\n> Ian Barwick\n>\n>\n> --\n> EnterpriseDB: https://www.enterprisedb.com\n>\n>\n>\nStatus update for a commitfest entry.\n\nThe patch is Waiting on Author for some time. As this is a bug fix, I am \nmoving it to the next CF.\nIan, are you planning to continue working on it?\n\n-- \nAnastasia Lubennikova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Tue, 1 Dec 2020 17:41:17 +0300", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Corner-case bug in pg_rewind" }, { "msg_contents": ">\n> Status update for a commitfest entry.\n>\n> The patch is Waiting on Author for some time. As this is a bug fix, I am\n> moving it to the next CF.\n> Ian, are you planning to continue working on it?\n>\n\nAs a reviewer, I consider the patch useful and good overall. The comments I\nleft were purely cosmetic. It's a pity to me that this bugfix delayed for\nsuch a small reason and outdated, therefore. It would be nice to complete\nthis fix on the next CF.\n\n-- \nBest regards,\nPavel Borisov\n\nPostgres Professional: http://postgrespro.com <http://www.postgrespro.com>\n\nStatus update for a commitfest entry.\n\nThe patch is Waiting on Author for some time. As this is a bug fix, I am \nmoving it to the next CF.\nIan, are you planning to continue working on it? As a reviewer, I consider the patch useful and good overall. The comments I left were purely cosmetic. It's a pity to me that this bugfix delayed for such a small reason and outdated, therefore. It would be nice to complete this fix on the next CF.-- Best regards,Pavel BorisovPostgres Professional: http://postgrespro.com", "msg_date": "Tue, 1 Dec 2020 18:52:05 +0400", "msg_from": "Pavel Borisov <pashkin.elfe@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Corner-case bug in pg_rewind" }, { "msg_contents": "On 01/12/2020 16:52, Pavel Borisov wrote:\n> Status update for a commitfest entry.\n> \n> The patch is Waiting on Author for some time. As this is a bug fix,\n> I am\n> moving it to the next CF.\n> Ian, are you planning to continue working on it?\n> \n> As a reviewer, I consider the patch useful and good overall. The \n> comments I left were purely cosmetic. It's a pity to me that this bugfix \n> delayed for such a small reason and outdated, therefore. It would be \n> nice to complete this fix on the next CF.\n\nYeah, we really should fix this..\n\nOn 16/11/2020 04:49, Ian Lawrence Barwick wrote:\n>> Also, I think Heikki's notion could be fulfilled.\n> \n> I spent a bit of time looking at that suggestion but couldn't actually\n> verify it was an issue which needed fixing.\n\nAttached are two patches. The first patch is your original patch, \nunmodified (except for a cosmetic rename of the test file). The second \npatch builds on that, demonstrating and fixing the issue I mentioned. It \ntook me a while to create a repro for it, it's easily masked by \nincidental full-page writes or because rows created by XIDs that are not \nmarked as committed on the other timeline are invisible, but succeeded \nat last.\n\n- Heikki", "msg_date": "Wed, 2 Dec 2020 13:13:38 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Corner-case bug in pg_rewind" }, { "msg_contents": "On 02/12/2020 20:13, Heikki Linnakangas wrote:\n> On 01/12/2020 16:52, Pavel Borisov wrote:\n>>     Status update for a commitfest entry.\n>>\n>>     The patch is Waiting on Author for some time. As this is a bug fix,\n>>     I am\n>>     moving it to the next CF.\n>>     Ian, are you planning to continue working on it?\n>>\n>> As a reviewer, I consider the patch useful and good overall. The comments I left were purely cosmetic. It's a pity to me that this bugfix delayed for such a small reason and outdated, therefore. It would be nice to complete this fix on the next CF.\n> \n> Yeah, we really should fix this..\n> \n> On 16/11/2020 04:49, Ian Lawrence Barwick wrote:\n>>> Also, I think Heikki's notion could be fulfilled.\n>>\n>> I spent a bit of time looking at that suggestion but couldn't actually\n>> verify it was an issue which needed fixing.\n >\n> Attached are two patches. The first patch is your original patch, unmodified\n> (except for a cosmetic rename of the test file). The second patch builds on\n> that, demonstrating and fixing the issue I mentioned. It took me a while to\n> create a repro for it, it's easily masked by incidental full-page writes or\n> because rows created by XIDs that are not marked as committed on the other\n> timeline are invisible, but succeeded at last.\n\nAha, many thanks. I wasn't entirely sure what I was looking for there and\nrecently haven't had the time or energy to dig any further.\n\n\nRegards\n\nIan Barwick\n\n-- \nIan Barwick https://www.2ndQuadrant.com/\n PostgreSQL Development, 24x7 Support, Training & Services\n\n\n", "msg_date": "Wed, 2 Dec 2020 22:26:53 +0900", "msg_from": "Ian Barwick <ian.barwick@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: Corner-case bug in pg_rewind" }, { "msg_contents": "On 02/12/2020 15:26, Ian Barwick wrote:\n> On 02/12/2020 20:13, Heikki Linnakangas wrote:\n>> Attached are two patches. The first patch is your original patch, unmodified\n>> (except for a cosmetic rename of the test file). The second patch builds on\n>> that, demonstrating and fixing the issue I mentioned. It took me a while to\n>> create a repro for it, it's easily masked by incidental full-page writes or\n>> because rows created by XIDs that are not marked as committed on the other\n>> timeline are invisible, but succeeded at last.\n> \n> Aha, many thanks. I wasn't entirely sure what I was looking for there and\n> recently haven't had the time or energy to dig any further.\n\nOk, pushed and backpatched this now.\n\nThanks!\n\n- Heikki\n\n\n", "msg_date": "Thu, 3 Dec 2020 16:10:47 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Corner-case bug in pg_rewind" }, { "msg_contents": ">\n> Ok, pushed and backpatched this now.\n>\nVery nice!\nThanks to you all!\n\n-- \nBest regards,\nPavel Borisov\n\nPostgres Professional: http://postgrespro.com <http://www.postgrespro.com>\n\nOk, pushed and backpatched this now.Very nice!Thanks to you all!-- Best regards,Pavel BorisovPostgres Professional: http://postgrespro.com", "msg_date": "Thu, 3 Dec 2020 18:49:37 +0400", "msg_from": "Pavel Borisov <pashkin.elfe@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Corner-case bug in pg_rewind" }, { "msg_contents": "On 03/12/2020 16:49, Pavel Borisov wrote:\n> Ok, pushed and backpatched this now.\n> \n> Very nice!\n> Thanks to you all!\n\nThanks for the review, Pavel! I just realized that I forgot to credit \nyou in the commit message. I'm sorry.\n\n- Heikki\n\n\n", "msg_date": "Thu, 3 Dec 2020 17:15:46 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Corner-case bug in pg_rewind" }, { "msg_contents": "чт, 3 дек. 2020 г. в 19:15, Heikki Linnakangas <hlinnaka@iki.fi>:\n\n> On 03/12/2020 16:49, Pavel Borisov wrote:\n> > Ok, pushed and backpatched this now.\n> >\n> > Very nice!\n> > Thanks to you all!\n>\n> Thanks for the review, Pavel! I just realized that I forgot to credit\n> you in the commit message. I'm sorry.\n>\nDon't worry, Heikki. No problem.\n-- \nBest regards,\nPavel Borisov\n\nPostgres Professional: http://postgrespro.com <http://www.postgrespro.com>\n\nчт, 3 дек. 2020 г. в 19:15, Heikki Linnakangas <hlinnaka@iki.fi>:On 03/12/2020 16:49, Pavel Borisov wrote:\n>     Ok, pushed and backpatched this now.\n> \n> Very nice!\n> Thanks to you all!\n\nThanks for the review, Pavel! I just realized that I forgot to credit \nyou in the commit message. I'm sorry.Don't worry, Heikki. No problem.-- Best regards,Pavel BorisovPostgres Professional: http://postgrespro.com", "msg_date": "Thu, 3 Dec 2020 19:50:44 +0400", "msg_from": "Pavel Borisov <pashkin.elfe@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Corner-case bug in pg_rewind" }, { "msg_contents": "On 03/12/2020 16:10, Heikki Linnakangas wrote:\n> On 02/12/2020 15:26, Ian Barwick wrote:\n>> On 02/12/2020 20:13, Heikki Linnakangas wrote:\n>>> Attached are two patches. The first patch is your original patch, unmodified\n>>> (except for a cosmetic rename of the test file). The second patch builds on\n>>> that, demonstrating and fixing the issue I mentioned. It took me a while to\n>>> create a repro for it, it's easily masked by incidental full-page writes or\n>>> because rows created by XIDs that are not marked as committed on the other\n>>> timeline are invisible, but succeeded at last.\n>>\n>> Aha, many thanks. I wasn't entirely sure what I was looking for there and\n>> recently haven't had the time or energy to dig any further.\n> \n> Ok, pushed and backpatched this now.\n\nThe buildfarm is reporting sporadic failures in the new regression test. \nI suspect it's because of timing issues, where a server is promoted or \nshut down before some data has been replicated. I'll fix that tomorrow \nmorning.\n\n- Heikki\n\n\n", "msg_date": "Fri, 4 Dec 2020 00:16:51 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Corner-case bug in pg_rewind" }, { "msg_contents": "On 04/12/2020 00:16, Heikki Linnakangas wrote:\n> On 03/12/2020 16:10, Heikki Linnakangas wrote:\n>> On 02/12/2020 15:26, Ian Barwick wrote:\n>>> On 02/12/2020 20:13, Heikki Linnakangas wrote:\n>>>> Attached are two patches. The first patch is your original patch, unmodified\n>>>> (except for a cosmetic rename of the test file). The second patch builds on\n>>>> that, demonstrating and fixing the issue I mentioned. It took me a while to\n>>>> create a repro for it, it's easily masked by incidental full-page writes or\n>>>> because rows created by XIDs that are not marked as committed on the other\n>>>> timeline are invisible, but succeeded at last.\n>>>\n>>> Aha, many thanks. I wasn't entirely sure what I was looking for there and\n>>> recently haven't had the time or energy to dig any further.\n>>\n>> Ok, pushed and backpatched this now.\n> \n> The buildfarm is reporting sporadic failures in the new regression test.\n> I suspect it's because of timing issues, where a server is promoted or\n> shut down before some data has been replicated. I'll fix that tomorrow\n> morning.\n\nFixed, I hope. It took me a while to backpatch, because small \ndifferences were needed in almost all versions, because some helpful TAP \ntest helpers like waiting for a standby to catchup are not available in \nbackbranches.\n\nThere was one curious difference between versions 9.6 and 10. In v10, \nyou can perform a \"clean switchover\" like this:\n\n1. Shut down primary (A) with \"pg_ctl -m fast\".\n\n2. Promote the standby (B) with \"pg_ctl promote\".\n\n3. Reconfigure the old primary (A) as a standby, by creating \nrecovery.conf that points to the promoted server, and start it up.\n\nBut on 9.6, that leads to an error on the the repurposed primary server (A):\n\nLOG: primary server contains no more WAL on requested timeline 1\nLOG: new timeline 2 forked off current database system timeline 1 \nbefore current recovery point 0/30000A0\n\nIt's not clear to me why that is. It seems that the primary generates \nsome WAL at shutdown that doesn't get replicated, before the shutdown \nhappens. Or the standby doesn't replay that WAL before it's promoted. \nBut we have supported \"clean switchover\" since 9.1, see commit \n985bd7d497. When you shut down the primary, it should wait until all the \nWAL has been replicated, including the shutdown checkpoint.\n\nPerhaps I was just doing it wrong in the test. Or maybe there's a \ngenuine bug in that that was fixed in v10. I worked around that in the \ntest by re-initializing the primary standby from backup instead of just \nreconfiguring it as a standby, and that's good enough for this \nparticular test, so I'm not planning to dig deeper into that myself.\n\n- Heikki\n\n\n", "msg_date": "Fri, 4 Dec 2020 18:43:24 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Corner-case bug in pg_rewind" } ]
[ { "msg_contents": "Hello\n\nJust arrived in the PostgreSQL world, and I'm looking for a solution to encrypt the database by using a TDE feature. Apparently this feature does not exist. Is it expected in the roadmap?\n\nThere is a fork named PostgreSQL 12.x TDE from Cybertec. The issue is that there is no key management at all.\n\nUsing pgcrypto has an impact on the application then I have to give up this way.\n\nThere is another alternative named \"Client-Side Encryption'' that I have not looked at in detail yet. I'm afraid that this solution has an impact on the application too. And if there are two applications pointing to the same database I am wondering how the encryption key is shared between the two nodes.\n\nThe last point is about the backups, whatever the solution, the data has to be in an encrypted format when \"backuping\".\n\nAny suggestions are welcome :). Thanks\n\n\n", "msg_date": "Fri, 11 Sep 2020 10:41:15 +0200 (CEST)", "msg_from": "laurent.feron@free.fr", "msg_from_op": true, "msg_subject": "TDE (Transparent Data Encryption) supported ?" }, { "msg_contents": "> On 11 Sep 2020, at 10:41, laurent.feron@free.fr wrote:\n\n> Just arrived in the PostgreSQL world,\n\nWelcome!\n\n> and I'm looking for a solution to encrypt the database by using a TDE feature. Apparently this feature does not exist. Is it expected in the roadmap?\n\nBeing entirely community driven, there is no roadmap per se. Individual\ndevelopers can have personal roadmaps, but at the end of the day it's the\ncollective development community that decide what goes in.\n\nThere is a wiki page which contains a lot of material on the attempts made so\nfar, with lots of links to discussions which may be of interest:\n\n https://wiki.postgresql.org/wiki/Transparent_Data_Encryption\n\n> The last point is about the backups, whatever the solution, the data has to be in an encrypted format when \"backuping\".\n\nThere are several backup tools which support PostgreSQL which can also encrypt\nthe data at rest in the archive. If thats what you're looking for then there\nshould be options available.\n\ncheers ./daniel\n\n", "msg_date": "Fri, 11 Sep 2020 13:18:52 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: TDE (Transparent Data Encryption) supported ?" }, { "msg_contents": "Greetings,\n\n* laurent.feron@free.fr (laurent.feron@free.fr) wrote:\n> There is a fork named PostgreSQL 12.x TDE from Cybertec. The issue is that there is no key management at all.\n\nKey management is definitely an understood issue in the community and\nthere was a fair bit of work put into trying to solve that problem last\nyear and hopefully that'll continue and perhaps be to a point where we\nhave a solution in v14. With that, perhaps we can also get TDE in, but\nthere certainly aren't any guarantees.\n\nWhat really needs to be considered, however, is what your attack vectors\nare and if TDE would really address them (often it doesn't, as with any\nTDE the keys end up at least in the memory of the database server and\ntherefore available to an attacker, not to mention that the data ends up\nbeing sent to the application unencrypted, and no, TLS/SSL doesn't help\nthat since an attacker on the server would be able to get at the data\nbefore it's wrapped in TLS).\n\n> Using pgcrypto has an impact on the application then I have to give up this way.\n\npgcrypto is an option but, again, the keys end up on the database server\nand therefore it may not be very helpful, depending on what the attack\nvector is that you're concerned about.\n\n> There is another alternative named \"Client-Side Encryption'' that I have not looked at in detail yet. I'm afraid that this solution has an impact on the application too. And if there are two applications pointing to the same database I am wondering how the encryption key is shared between the two nodes.\n\nPerforming encryption of the sensitive data as early as possible is\ncertainly the best answer, and that means doing it in the application\nbefore it ever reaches the database server. Yes, that means that\nchanges have to be made to the application, but it's a much better\nsolution which will actually address real attack vectors, like the\ndatabase server being compromised.\n\nIn general, as it relates to multiple applications connecting to the\nsame database- I'd just downright discourage that. PG is much lighter\nweight than other RDBMS solutions and you don't need to have 100\ndifferent applications connecting to the same database server- instead\nhave an independent cluster for each application and use certificates or\nother strong authentication mechanism to make sure that app A can only\nconnect to the PG cluster for app A and not to any others- this\ncompletely removes the concern about an SQL injection attack on app A\nallowing the attacker to gain access to app B's data.\n\nAnother advantage of this is that the individual clusters are smaller,\nand they can be scaled independently, backed up independently, and\nrestored independently, all of which are really good things.\n\n> The last point is about the backups, whatever the solution, the data has to be in an encrypted format when \"backuping\".\n\nUse a backup technology that provides encryption- pgbackrest does, and\nsome others probably do too.\n\nThanks,\n\nStephen", "msg_date": "Fri, 11 Sep 2020 11:19:21 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: TDE (Transparent Data Encryption) supported ?" }, { "msg_contents": "Thank for your responses\nI come back to your comments about vestor attacks. I know that TDE protects against disk thefts, not really more ..\nBut compagnie has some internal rules and some of them require \"At Rest\" encryption, nothing more is mentionned.\nThen, even if TDE is not THE solution in term of security, it is something that companies want.\nLaurent\n\n----- Mail original -----\nDe: \"Stephen Frost\" <sfrost@snowman.net>\nÀ: \"laurent feron\" <laurent.feron@free.fr>\nCc: pgsql-hackers@lists.postgresql.org\nEnvoyé: Vendredi 11 Septembre 2020 17:19:21\nObjet: Re: TDE (Transparent Data Encryption) supported ?\n\nGreetings,\n\n* laurent.feron@free.fr (laurent.feron@free.fr) wrote:\n> There is a fork named PostgreSQL 12.x TDE from Cybertec. The issue is that there is no key management at all.\n\nKey management is definitely an understood issue in the community and\nthere was a fair bit of work put into trying to solve that problem last\nyear and hopefully that'll continue and perhaps be to a point where we\nhave a solution in v14. With that, perhaps we can also get TDE in, but\nthere certainly aren't any guarantees.\n\nWhat really needs to be considered, however, is what your attack vectors\nare and if TDE would really address them (often it doesn't, as with any\nTDE the keys end up at least in the memory of the database server and\ntherefore available to an attacker, not to mention that the data ends up\nbeing sent to the application unencrypted, and no, TLS/SSL doesn't help\nthat since an attacker on the server would be able to get at the data\nbefore it's wrapped in TLS).\n\n> Using pgcrypto has an impact on the application then I have to give up this way.\n\npgcrypto is an option but, again, the keys end up on the database server\nand therefore it may not be very helpful, depending on what the attack\nvector is that you're concerned about.\n\n> There is another alternative named \"Client-Side Encryption'' that I have not looked at in detail yet. I'm afraid that this solution has an impact on the application too. And if there are two applications pointing to the same database I am wondering how the encryption key is shared between the two nodes.\n\nPerforming encryption of the sensitive data as early as possible is\ncertainly the best answer, and that means doing it in the application\nbefore it ever reaches the database server. Yes, that means that\nchanges have to be made to the application, but it's a much better\nsolution which will actually address real attack vectors, like the\ndatabase server being compromised.\n\nIn general, as it relates to multiple applications connecting to the\nsame database- I'd just downright discourage that. PG is much lighter\nweight than other RDBMS solutions and you don't need to have 100\ndifferent applications connecting to the same database server- instead\nhave an independent cluster for each application and use certificates or\nother strong authentication mechanism to make sure that app A can only\nconnect to the PG cluster for app A and not to any others- this\ncompletely removes the concern about an SQL injection attack on app A\nallowing the attacker to gain access to app B's data.\n\nAnother advantage of this is that the individual clusters are smaller,\nand they can be scaled independently, backed up independently, and\nrestored independently, all of which are really good things.\n\n> The last point is about the backups, whatever the solution, the data has to be in an encrypted format when \"backuping\".\n\nUse a backup technology that provides encryption- pgbackrest does, and\nsome others probably do too.\n\nThanks,\n\nStephen\n\n\n", "msg_date": "Mon, 14 Sep 2020 10:29:32 +0200 (CEST)", "msg_from": "laurent.feron@free.fr", "msg_from_op": true, "msg_subject": "Re: TDE (Transparent Data Encryption) supported ?" }, { "msg_contents": "hi …\n\nwell, the reason why there is no key management is that we wanted to keep the interface open so that people \ncan integrate with everything they want. i have seen keymanagement tools come and go.\npostgresql is certainly gonna live longer than many of those things.\nthus we intentionally decided to be flexible here.\n\nas for postgresql 14: we are certainly willing to push that into 14 but the past couple of years\non the TDE front have been a little frustrating for us.\nit seems we cannot reach consensus so it is pretty likely that we have to\nkeep maintaining it separately. i would love to see it in core but i don’t expect that to happen\nunder current circumstances. \n\n\tmany thanks,\n\n\t\thans\n\n\n\n> On 11.09.2020, at 17:19, Stephen Frost <sfrost@snowman.net> wrote:\n> \n> Greetings,\n> \n> * laurent.feron@free.fr (laurent.feron@free.fr) wrote:\n>> There is a fork named PostgreSQL 12.x TDE from Cybertec. The issue is that there is no key management at all.\n> \n> Key management is definitely an understood issue in the community and\n> there was a fair bit of work put into trying to solve that problem last\n> year and hopefully that'll continue and perhaps be to a point where we\n> have a solution in v14. With that, perhaps we can also get TDE in, but\n> there certainly aren't any guarantees.\n> \n> What really needs to be considered, however, is what your attack vectors\n> are and if TDE would really address them (often it doesn't, as with any\n> TDE the keys end up at least in the memory of the database server and\n> therefore available to an attacker, not to mention that the data ends up\n> being sent to the application unencrypted, and no, TLS/SSL doesn't help\n> that since an attacker on the server would be able to get at the data\n> before it's wrapped in TLS).\n> \n>> Using pgcrypto has an impact on the application then I have to give up this way.\n> \n> pgcrypto is an option but, again, the keys end up on the database server\n> and therefore it may not be very helpful, depending on what the attack\n> vector is that you're concerned about.\n> \n>> There is another alternative named \"Client-Side Encryption'' that I have not looked at in detail yet. I'm afraid that this solution has an impact on the application too. And if there are two applications pointing to the same database I am wondering how the encryption key is shared between the two nodes.\n> \n> Performing encryption of the sensitive data as early as possible is\n> certainly the best answer, and that means doing it in the application\n> before it ever reaches the database server. Yes, that means that\n> changes have to be made to the application, but it's a much better\n> solution which will actually address real attack vectors, like the\n> database server being compromised.\n> \n> In general, as it relates to multiple applications connecting to the\n> same database- I'd just downright discourage that. PG is much lighter\n> weight than other RDBMS solutions and you don't need to have 100\n> different applications connecting to the same database server- instead\n> have an independent cluster for each application and use certificates or\n> other strong authentication mechanism to make sure that app A can only\n> connect to the PG cluster for app A and not to any others- this\n> completely removes the concern about an SQL injection attack on app A\n> allowing the attacker to gain access to app B's data.\n> \n> Another advantage of this is that the individual clusters are smaller,\n> and they can be scaled independently, backed up independently, and\n> restored independently, all of which are really good things.\n> \n>> The last point is about the backups, whatever the solution, the data has to be in an encrypted format when \"backuping\".\n> \n> Use a backup technology that provides encryption- pgbackrest does, and\n> some others probably do too.\n> \n> Thanks,\n> \n> Stephen\n\n--\nCybertec PostgreSQL International GmbH\nGröhrmühlgasse 26, A-2700 Wiener Neustadt\nWeb: https://www.cybertec-postgresql.com <https://www.cybertec-postgresql.com/>\n\n\n\n\n\n\n\n\n\nhi …well, the reason why there is no key management is that we wanted to keep the interface open so that people can integrate with everything they want. i have seen keymanagement tools come and go.postgresql is certainly gonna live longer than many of those things.thus we intentionally decided to be flexible here.as for postgresql 14: we are certainly willing to push that into 14 but the past couple of yearson the TDE front have been a little frustrating for us.it seems we cannot reach consensus so it is pretty likely that we have tokeep maintaining it separately. i would love to see it in core but i don’t expect that to happenunder current circumstances.  many thanks, hansOn 11.09.2020, at 17:19, Stephen Frost <sfrost@snowman.net> wrote:Greetings,* laurent.feron@free.fr (laurent.feron@free.fr) wrote:There is a fork named PostgreSQL 12.x TDE from Cybertec. The issue is that there is no key management at all.Key management is definitely an understood issue in the community andthere was a fair bit of work put into trying to solve that problem lastyear and hopefully that'll continue and perhaps be to a point where wehave a solution in v14.  With that, perhaps we can also get TDE in, butthere certainly aren't any guarantees.What really needs to be considered, however, is what your attack vectorsare and if TDE would really address them (often it doesn't, as with anyTDE the keys end up at least in the memory of the database server andtherefore available to an attacker, not to mention that the data ends upbeing sent to the application unencrypted, and no, TLS/SSL doesn't helpthat since an attacker on the server would be able to get at the databefore it's wrapped in TLS).Using pgcrypto has an impact on the application then I have to give up this way.pgcrypto is an option but, again, the keys end up on the database serverand therefore it may not be very helpful, depending on what the attackvector is that you're concerned about.There is another alternative named \"Client-Side Encryption'' that I have not looked at in detail yet. I'm afraid that this solution has an impact on the application too. And if there are two applications pointing to the same database I am wondering how the encryption key is shared between the two nodes.Performing encryption of the sensitive data as early as possible iscertainly the best answer, and that means doing it in the applicationbefore it ever reaches the database server.  Yes, that means thatchanges have to be made to the application, but it's a much bettersolution which will actually address real attack vectors, like thedatabase server being compromised.In general, as it relates to multiple applications connecting to thesame database- I'd just downright discourage that.  PG is much lighterweight than other RDBMS solutions and you don't need to have 100different applications connecting to the same database server- insteadhave an independent cluster for each application and use certificates orother strong authentication mechanism to make sure that app A can onlyconnect to the PG cluster for app A and not to any others- thiscompletely removes the concern about an SQL injection attack on app Aallowing the attacker to gain access to app B's data.Another advantage of this is that the individual clusters are smaller,and they can be scaled independently, backed up independently, andrestored independently, all of which are really good things.The last point is about the backups, whatever the solution, the data has to be in an encrypted format when \"backuping\".Use a backup technology that provides encryption- pgbackrest does, andsome others probably do too.Thanks,Stephen\n--Cybertec PostgreSQL International GmbHGröhrmühlgasse 26, A-2700 Wiener Neustadt\nWeb: https://www.cybertec-postgresql.com", "msg_date": "Mon, 14 Sep 2020 14:01:21 +0200", "msg_from": "=?utf-8?B?IkhhbnMtSsO8cmdlbiBTY2jDtm5pZyAoUG9zdGdyZVNRTCki?=\n <postgres@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: TDE (Transparent Data Encryption) supported ?" }, { "msg_contents": "Greetings,\n\nWe'd prefer it if you didn't top-post (just write some stuff at the top)\nwhen you respond and post to these mailing lists.\n\n* laurent.feron@free.fr (laurent.feron@free.fr) wrote:\n> I come back to your comments about vestor attacks. I know that TDE protects against disk thefts, not really more ..\n\nThat is a data-at-rest concern and TDE is one approach to addressing it.\n\n> But compagnie has some internal rules and some of them require \"At Rest\" encryption, nothing more is mentionned.\n> Then, even if TDE is not THE solution in term of security, it is something that companies want.\n\nDisk-based encryption is available for basically all operating systems\nand PostgreSQL works reasonably well on top of encrypted filesystems or\nblock devices. That's all available today, works quite well to deal\nwith the \"someone stole the disk\" or \"someone forgot to wipe the drive\nbefore throwing it away\" attack vectors.\n\nIn particular, I'd encourage you to look at Linux with LUKS for data at\nrest encryption. You can then simply run PostgreSQL on top of that and\nbe protected without any of the complications which TDE introduces.\n\nThanks,\n\nStephen", "msg_date": "Mon, 14 Sep 2020 08:39:42 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: TDE (Transparent Data Encryption) supported ?" } ]
[ { "msg_contents": "Hi hackers:\n\nIn file src/backend/catalog/pg_cast.c in branch REL_13_STABLE(also in branch master)\nhttps://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/catalog/pg_cast.c;h=5ea2b82b083477777c2a82b8d1a4588e4530f92e;hb=refs/heads/REL_13_STABLE\n\nthe copyright is still\nPortions Copyright (c) 1996-2019, PostgreSQL Global Development Group\n\n\nShould it be update to '1996-2020' before REL_13_RC1 released?\n\nBest wishes\n\nThanks\n\n\n\n\n", "msg_date": "Fri, 11 Sep 2020 08:42:13 +0000", "msg_from": "\"Wang, Shenhao\" <wangsh.fnst@cn.fujitsu.com>", "msg_from_op": true, "msg_subject": "copyright problem in REL_13_STABLE" }, { "msg_contents": "> On 11 Sep 2020, at 10:42, Wang, Shenhao <wangsh.fnst@cn.fujitsu.com> wrote:\n\n> the copyright is still\n> Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group\n> \n> Should it be update to '1996-2020' before REL_13_RC1 released?\n\nNice catch, the file was added after the 2020 copyright update so should\ndefinitely have 1996-2020 as the copyright range. This is probably just a\ncopy-pasteo in 40b3e2c201a, cc:ing Álvaro.\n\ncheers ./daniel\n\n", "msg_date": "Fri, 11 Sep 2020 13:11:06 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: copyright problem in REL_13_STABLE" }, { "msg_contents": "On 2020-Sep-11, Daniel Gustafsson wrote:\n\n> > On 11 Sep 2020, at 10:42, Wang, Shenhao <wangsh.fnst@cn.fujitsu.com> wrote:\n> \n> > the copyright is still\n> > Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group\n> > \n> > Should it be update to '1996-2020' before REL_13_RC1 released?\n> \n> Nice catch, the file was added after the 2020 copyright update so should\n> definitely have 1996-2020 as the copyright range. This is probably just a\n> copy-pasteo in 40b3e2c201a, cc:ing �lvaro.\n\nYeah, I wrote the file in 2019 and forgot to update the copyright stmt\nwhen committing. Will fix.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 11 Sep 2020 09:47:33 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: copyright problem in REL_13_STABLE" } ]
[ { "msg_contents": "Looking at a pg_dump patch I realized that when we call buildIndexArray without\nhaving found objects to index, we still call pg_malloc with zero which in turn\nmallocs 1 byte. The byte in question is of course negligable, but it does seem\ncleaner to return early with NULL instead of returning an empty allocation\nwhich doesn't actually contain an index.\n\nAny reason not to bail early as per the attached?\n\ncheers ./daniel", "msg_date": "Fri, 11 Sep 2020 13:38:29 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": true, "msg_subject": "Avoid incorrect allocation in buildIndexArray" }, { "msg_contents": "On Fri, Sep 11, 2020 at 1:39 PM Daniel Gustafsson <daniel@yesql.se> wrote:\n>\n> Looking at a pg_dump patch I realized that when we call buildIndexArray without\n> having found objects to index, we still call pg_malloc with zero which in turn\n> mallocs 1 byte. The byte in question is of course negligable, but it does seem\n> cleaner to return early with NULL instead of returning an empty allocation\n> which doesn't actually contain an index.\n>\n> Any reason not to bail early as per the attached?\n\n+1\n\n\n", "msg_date": "Fri, 11 Sep 2020 13:49:26 +0200", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Avoid incorrect allocation in buildIndexArray" }, { "msg_contents": "On Fri, Sep 11, 2020 at 01:49:26PM +0200, Julien Rouhaud wrote:\n> On Fri, Sep 11, 2020 at 1:39 PM Daniel Gustafsson <daniel@yesql.se> wrote:\n>> Any reason not to bail early as per the attached?\n> \n> +1\n\nMakes sense to me. This has also the advantage to cause a crash if\nthere is an attempt to refer to those empty arrays in case of future\nrefactoring, which is rather defensive. By looking at\nfindObjectByOid(), I can also see that we check for a negative number,\nso I concur with Ranier's comment to check after that on top of 0.\nIf there are no objections, I'll apply that on HEAD.\n--\nMichael", "msg_date": "Sat, 12 Sep 2020 18:13:56 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Avoid incorrect allocation in buildIndexArray" }, { "msg_contents": "Le sam. 12 sept. 2020 à 11:14, Michael Paquier <michael@paquier.xyz> a\nécrit :\n\n> On Fri, Sep 11, 2020 at 01:49:26PM +0200, Julien Rouhaud wrote:\n> > On Fri, Sep 11, 2020 at 1:39 PM Daniel Gustafsson <daniel@yesql.se>\n> wrote:\n> >> Any reason not to bail early as per the attached?\n> >\n> > +1\n>\n> Makes sense to me. This has also the advantage to cause a crash if\n> there is an attempt to refer to those empty arrays in case of future\n> refactoring, which is rather defensive. By looking at\n> findObjectByOid(), I can also see that we check for a negative number,\n>\n\nyes, I also checked that current code is already checking for that.\n\nso I concur with Ranier's comment to check after that on top of 0.\n> If there are no objections, I'll apply that on HEAD.\n\n\nagreed.\n\n>\n\nLe sam. 12 sept. 2020 à 11:14, Michael Paquier <michael@paquier.xyz> a écrit :On Fri, Sep 11, 2020 at 01:49:26PM +0200, Julien Rouhaud wrote:\n> On Fri, Sep 11, 2020 at 1:39 PM Daniel Gustafsson <daniel@yesql.se> wrote:\n>> Any reason not to bail early as per the attached?\n> \n> +1\n\nMakes sense to me.  This has also the advantage to cause a crash if\nthere is an attempt to refer to those empty arrays in case of future\nrefactoring, which is rather defensive.  By looking at\nfindObjectByOid(), I can also see that we check for a negative number,yes, I also checked that current code is already checking for that. \nso I concur with Ranier's comment to check after that on top of 0.\nIf there are no objections, I'll apply that on HEAD.agreed.", "msg_date": "Sat, 12 Sep 2020 12:40:49 +0200", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Avoid incorrect allocation in buildIndexArray" }, { "msg_contents": "On Sat, Sep 12, 2020 at 12:40:49PM +0200, Julien Rouhaud wrote:\n> agreed.\n\nOk, done as ac673a1 then.\n--\nMichael", "msg_date": "Mon, 14 Sep 2020 10:45:49 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Avoid incorrect allocation in buildIndexArray" }, { "msg_contents": "Em dom., 13 de set. de 2020 às 22:46, Michael Paquier <michael@paquier.xyz>\nescreveu:\n\n> On Sat, Sep 12, 2020 at 12:40:49PM +0200, Julien Rouhaud wrote:\n> > agreed.\n>\n> Ok, done as ac673a1 then.\n>\nThanks Michael.\n\nregards,\nRanier Vilela\n\nEm dom., 13 de set. de 2020 às 22:46, Michael Paquier <michael@paquier.xyz> escreveu:On Sat, Sep 12, 2020 at 12:40:49PM +0200, Julien Rouhaud wrote:\n> agreed.\n\nOk, done as ac673a1 then.Thanks Michael.regards,Ranier Vilela", "msg_date": "Mon, 14 Sep 2020 08:49:38 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Avoid incorrect allocation in buildIndexArray" } ]
[ { "msg_contents": "On Fri, Sep 11, 2020 at 1:39 PM Daniel Gustafsson <daniel(at)yesql(dot)se>\nwrote:\n>\n> Looking at a pg_dump patch I realized that when we call buildIndexArray\nwithout\n> having found objects to index, we still call pg_malloc with zero which in\nturn\n> mallocs 1 byte. The byte in question is of course negligable, but it does\nseem\n> cleaner to return early with NULL instead of returning an empty allocation\n> which doesn't actually contain an index.\n>\n> Any reason not to bail early as per the attached?\n+1\n\nSince, it is protecting from invalid entries.\nnumObjs is int, the better it would be then.\n+ if (numObjs <= 0)\n+ return NULL;\n+\n\nregards,\nRanier Vilela\n\n\nOn Fri, Sep 11, 2020 at 1:39 PM Daniel Gustafsson <daniel(at)yesql(dot)se> wrote:>> Looking at a pg_dump patch I realized that when we call buildIndexArray without> having found objects to index, we still call pg_malloc with zero which in turn> mallocs 1 byte. The byte in question is of course negligable, but it does seem> cleaner to return early with NULL instead of returning an empty allocation> which doesn't actually contain an index.>> Any reason not to bail early as per the attached?\n+1Since, it is protecting from invalid entries.numObjs is int, the better it would be then.+\tif (numObjs <= 0)+\t\treturn NULL;+regards,Ranier Vilela", "msg_date": "Fri, 11 Sep 2020 08:56:58 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Avoid incorrect allocation in buildIndexArray" } ]
[ { "msg_contents": "Right now, pg_service.conf returns \"syntax error\" if it encounters a\nparameter it doesn't know about.\n\nThis seems user-unfriendly, both in the error message (because it really\nisn't a syntax error) and in the behaviour itself (because it doesn't work\nwhen sometimes it should).\n\nFor example, if I have a service file with gssencmode=disable set, that\nservice file cannot be used by a psql client linked against libpq from\nversion 10. Even if the behavior would be identical (since v10 doesn't have\ngssencmode).\n\nIs there a particular reason we (1) refuse unknown parameters in the file,\nand (2) call it a \"syntax error\"?\n\nThe documentation just says it's \"INI format\" file -- though in my\nexperience most other INI file parsers just ignore extra parameters\nincluded..\n\n//Magnus\n\nRight now, pg_service.conf returns \"syntax error\" if it encounters a parameter it doesn't know about.This seems user-unfriendly, both in the error message (because it really isn't a syntax error) and in the behaviour itself (because it doesn't work when sometimes it should).For example, if I have a service file with gssencmode=disable set, that service file cannot be used by a psql client linked against libpq from version 10. Even if the behavior would be identical (since v10 doesn't have gssencmode).Is there a particular reason we (1) refuse unknown parameters in the file, and (2) call it a \"syntax error\"?The documentation just says it's \"INI format\" file -- though in my experience most other INI file parsers just ignore extra parameters included..//Magnus", "msg_date": "Fri, 11 Sep 2020 14:39:51 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": true, "msg_subject": "pg_service.conf file with unknown parameters" }, { "msg_contents": "On Fri, Sep 11, 2020 at 02:39:51PM +0200, Magnus Hagander wrote:\n> Right now, pg_service.conf returns \"syntax error\" if it encounters a parameter\n> it doesn't know about.\n> \n> This seems user-unfriendly, both in the error message (because it really isn't\n> a syntax error) and in the behaviour itself (because it doesn't work when\n> sometimes it should).\n> \n> For example, if I have a service file with gssencmode=disable set, that service\n> file cannot be used by a psql client linked against libpq from version 10. Even\n> if the behavior would be identical (since v10 doesn't have gssencmode).\n> \n> Is there a particular reason we (1) refuse unknown parameters in the file, and\n> (2) call it a \"syntax error\"?\n> \n> The documentation just says it's \"INI format\" file -- though in my experience\n> most other INI file parsers just ignore extra parameters included..\n\nMy guess is that because the file can contain passwords, we want to\nreport as little as possible on error.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Fri, 18 Sep 2020 19:32:01 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: pg_service.conf file with unknown parameters" }, { "msg_contents": "> On 11 Sep 2020, at 14:39, Magnus Hagander <magnus@hagander.net> wrote:\n\n> For example, if I have a service file with gssencmode=disable set, that service file cannot be used by a psql client linked against libpq from version 10. Even if the behavior would be identical (since v10 doesn't have gssencmode).\n> \n> Is there a particular reason we (1) refuse unknown parameters in the file,\n\nThe above case is a good example when silently ignoring would be beneficial.\nWe would however run the risk that someone has this in their service which is\nsilently ignored and fails to notice:\n\n ssl_mim_protocol_version=TLSv1.3\n\nNot sure if that's worth the risk? Halting on unknown parameters is also\nconsistent with postgresql.conf parsing etc (which isn't a clientside file I\nknow, but still relevant IMO).\n\n> and (2) call it a \"syntax error\"?\n\nThat I agree with isn't entirely correct, the syntax is correct but the\nparameter is unknown. Something along the following seems more correct:\n\n - libpq_gettext(\"syntax error in service file \\\"%s\\\", line %d\\n\"),\n + libpq_gettext(\"unknown parameter in service file \\\"%s\\\", line %d\\n\"),\n\n> The documentation just says it's \"INI format\" file -- though in my experience most other INI file parsers just ignore extra parameters included..\n\nI don't think the INI file format is formally defined anywhere, but I do\nbelieve it's considered to be strictly key-values (Wikipedia [0] agrees with\nthat). Since we allow ldap configurations like the one below, it's technically\nnot INI format though:\n\n [service=mydb]\n ldap://127.0.0.1:10000/foo?bar?lorem?ipsum\n\nThat might be borderline hairsplitting, but perhaps calling it INI format in\nthe docs isn't really helping? Maybe we should reword that to say key/value or\nsomething similar?\n\nAnd this brings up an even more interesting case, the above will yield a syntax\nerror if libpq wasn't compiled with LDAP support, as opposed to other\nparameters (like SSL* etc) which are ignored for builds not supporting them.\nIs there a reason to treat ldap differently?\n\ncheers ./daniel\n\n[0] https://en.wikipedia.org/wiki/INI_file\n\n", "msg_date": "Mon, 21 Sep 2020 13:28:08 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: pg_service.conf file with unknown parameters" } ]
[ { "msg_contents": "Hi,\n\nread_binary_file seems a bit complicated when we want to read the rest of\nthe file (-1 for bytes_to_read).\nThis version, it seems, has no opposite effects, someone can confirm?\n\nregards,\nRanier Vilela", "msg_date": "Fri, 11 Sep 2020 11:50:37 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Simplified version of read_binary_file\n (src/backend/utils/adt/genfile.c)" }, { "msg_contents": "On 2020-Sep-11, Ranier Vilela wrote:\n\n> Hi,\n> \n> read_binary_file seems a bit complicated when we want to read the rest of\n> the file (-1 for bytes_to_read).\n\nThis code was very recently rewritten in 96d1f423f95d, and I doubt that\ntaking out half the algorithm without studying how it got that way is a\ngreat idea.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 11 Sep 2020 14:01:04 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Simplified version of read_binary_file\n (src/backend/utils/adt/genfile.c)" }, { "msg_contents": "Em sex., 11 de set. de 2020 às 14:01, Alvaro Herrera <\nalvherre@2ndquadrant.com> escreveu:\n\n> On 2020-Sep-11, Ranier Vilela wrote:\n>\n> > Hi,\n> >\n> > read_binary_file seems a bit complicated when we want to read the rest of\n> > the file (-1 for bytes_to_read).\n>\n> This code was very recently rewritten in 96d1f423f95d, and I doubt that\n> taking out half the algorithm without studying how it got that way is a\n> great idea.\n>\nWorks with all regress tests (199, same as the HEAD with msvc 2019 64 bits\nexcept partition_prune)\nWorks with pgbench (pgbench -U postgres -c 50 -j 2 -t 10000 example)\nAnd works with local installation, without adverse effects, for now.\n\nregards,\nRanier Vilela\n\nEm sex., 11 de set. de 2020 às 14:01, Alvaro Herrera <alvherre@2ndquadrant.com> escreveu:On 2020-Sep-11, Ranier Vilela wrote:\n\n> Hi,\n> \n> read_binary_file seems a bit complicated when we want to read the rest of\n> the file (-1 for bytes_to_read).\n\nThis code was very recently rewritten in 96d1f423f95d, and I doubt that\ntaking out half the algorithm without studying how it got that way is a\ngreat idea.Works with all regress tests (199, same as the HEAD with msvc 2019 64 bits except partition_prune)Works with pgbench (pgbench -U postgres -c 50 -j 2 -t 10000 example)And works with local installation, without adverse effects, for now.regards,Ranier Vilela", "msg_date": "Fri, 11 Sep 2020 14:10:31 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Simplified version of read_binary_file\n (src/backend/utils/adt/genfile.c)" }, { "msg_contents": "On 2020-09-11 14:10:31 -0300, Ranier Vilela wrote:\n> Em sex., 11 de set. de 2020 �s 14:01, Alvaro Herrera <\n> alvherre@2ndquadrant.com> escreveu:\n> > On 2020-Sep-11, Ranier Vilela wrote:\n> > This code was very recently rewritten in 96d1f423f95d, and I doubt that\n> > taking out half the algorithm without studying how it got that way is a\n> > great idea.\n> >\n> Works with all regress tests (199, same as the HEAD with msvc 2019 64 bits\n> except partition_prune)\n> Works with pgbench (pgbench -U postgres -c 50 -j 2 -t 10000 example)\n> And works with local installation, without adverse effects, for now.\n\nHave your read the commit message for 96d1f423f95d ?\n\n\n", "msg_date": "Fri, 11 Sep 2020 11:09:30 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Simplified version of read_binary_file\n (src/backend/utils/adt/genfile.c)" }, { "msg_contents": "Em sex., 11 de set. de 2020 às 15:09, Andres Freund <andres@anarazel.de>\nescreveu:\n\n> On 2020-09-11 14:10:31 -0300, Ranier Vilela wrote:\n> > Em sex., 11 de set. de 2020 às 14:01, Alvaro Herrera <\n> > alvherre@2ndquadrant.com> escreveu:\n> > > On 2020-Sep-11, Ranier Vilela wrote:\n> > > This code was very recently rewritten in 96d1f423f95d, and I doubt that\n> > > taking out half the algorithm without studying how it got that way is a\n> > > great idea.\n> > >\n> > Works with all regress tests (199, same as the HEAD with msvc 2019 64\n> bits\n> > except partition_prune)\n> > Works with pgbench (pgbench -U postgres -c 50 -j 2 -t 10000 example)\n> > And works with local installation, without adverse effects, for now.\n>\n> Have your read the commit message for 96d1f423f95d ?\n>\nYead, I read.\nHe's concerned about virtual file (pipe, FIFO, socket).\nThe patch ( 96d1f423f95d ) has the same problem.\nfseeko with virtual file can fail too.\n\nhttps://man7.org/linux/man-pages/man3/fseek.3.html\nESPIPE The file descriptor underlying stream is not seekable (e.g.,\n it refers to a pipe, FIFO, or socket)\n\nCall read_binary_file with virtual file,will log in:\n\"could not seek in file\"\n\nregards,\nRanier Vilela\n\nEm sex., 11 de set. de 2020 às 15:09, Andres Freund <andres@anarazel.de> escreveu:On 2020-09-11 14:10:31 -0300, Ranier Vilela wrote:\n> Em sex., 11 de set. de 2020 às 14:01, Alvaro Herrera <\n> alvherre@2ndquadrant.com> escreveu:\n> > On 2020-Sep-11, Ranier Vilela wrote:\n> > This code was very recently rewritten in 96d1f423f95d, and I doubt that\n> > taking out half the algorithm without studying how it got that way is a\n> > great idea.\n> >\n> Works with all regress tests (199, same as the HEAD with msvc 2019 64 bits\n> except partition_prune)\n> Works with pgbench (pgbench -U postgres -c 50 -j 2 -t 10000 example)\n> And works with local installation, without adverse effects, for now.\n\nHave your read the commit message for 96d1f423f95d ?Yead, I read.He's concerned about virtual file (pipe, FIFO, socket).The patch (\n96d1f423f95d\n\n) has the same problem.fseeko with virtual file can fail too.https://man7.org/linux/man-pages/man3/fseek.3.htmlESPIPE The file descriptor underlying stream is not seekable (e.g.,              it refers to a pipe, FIFO, or socket)Call read_binary_file with virtual file,will log in:\"could not seek in file\"regards,Ranier Vilela", "msg_date": "Fri, 11 Sep 2020 16:09:03 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Simplified version of read_binary_file\n (src/backend/utils/adt/genfile.c)" }, { "msg_contents": "New version, with support to read Virtual File (pipe, FIFO and socket).\nWith assert, in case, erroneous, of trying to read a pipe, with offset.\n\nregards,\nRanier Vilela", "msg_date": "Fri, 11 Sep 2020 17:02:03 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Simplified version of read_binary_file\n (src/backend/utils/adt/genfile.c)" }, { "msg_contents": "Ranier Vilela <ranier.vf@gmail.com> writes:\n> New version, with support to read Virtual File (pipe, FIFO and socket).\n> With assert, in case, erroneous, of trying to read a pipe, with offset.\n\nReally, could you do a little more thinking and testing of your own,\nrather than expecting the rest of us to point out holes in your thinking?\n\n* bytes_to_read == 0 is a legal case.\n\n* \"Assert(seek_offset != 0)\" is an equally awful idea.\n\n* Removing the seek code from the negative-bytes_to_read path\nis just broken.\n\n* The only reason this code is shorter than the previous version is\nyou took out all the comments explaining what it was doing, and\nfailed to replace them. This is just as subtle as before, so I\ndon't find that acceptable.\n\nI do agree that it might be worth skipping the fseeko call in the\nprobably-common case where seek_offset is zero. Otherwise I don't\nsee much reason to change what's there.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 11 Sep 2020 16:44:25 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Simplified version of read_binary_file\n (src/backend/utils/adt/genfile.c)" }, { "msg_contents": "Em sex., 11 de set. de 2020 às 17:44, Tom Lane <tgl@sss.pgh.pa.us> escreveu:\n\n> Ranier Vilela <ranier.vf@gmail.com> writes:\n> > New version, with support to read Virtual File (pipe, FIFO and socket).\n> > With assert, in case, erroneous, of trying to read a pipe, with offset.\n>\n> Really, could you do a little more thinking and testing of your own,\n> rather than expecting the rest of us to point out holes in your thinking?\n>\nYes, I can.\n\n\n> * bytes_to_read == 0 is a legal case.\n>\nOk. Strange call to read a file with zero bytes.\n\n\n> * \"Assert(seek_offset != 0)\" is an equally awful idea.\n>\nI was trying to predict the case of reading a Virtual File, with\nbytes_to_read == -1 and seek_offset == 0,\nwhich is bound to fail in fseeko.\nIn any case, 96d1f423f95d it will fail with any Virtual File.\n\n\n>\n> * Removing the seek code from the negative-bytes_to_read path\n> is just broken.\n>\nOk.\n\n\n> * The only reason this code is shorter than the previous version is\n> you took out all the comments explaining what it was doing, and\n> failed to replace them. This is just as subtle as before, so I\n> don't find that acceptable.\n>\nIt was not my intention.\n\n\n>\n> I do agree that it might be worth skipping the fseeko call in the\n> probably-common case where seek_offset is zero. Otherwise I don't\n> see much reason to change what's there.\n>\nWell, I think that v3 is a little better, but it’s just my opinion.\nv3 try to copy directly in the final buffer, which will certainly be a\nlittle faster.\n\nregards,\nRanier Vilela", "msg_date": "Fri, 11 Sep 2020 18:43:48 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Simplified version of read_binary_file\n (src/backend/utils/adt/genfile.c)" }, { "msg_contents": "Em sex., 11 de set. de 2020 às 17:44, Tom Lane <tgl@sss.pgh.pa.us> escreveu:\n\n> Ranier Vilela <ranier.vf@gmail.com> writes:\n> > New version, with support to read Virtual File (pipe, FIFO and socket).\n> > With assert, in case, erroneous, of trying to read a pipe, with offset.\n>\n> I do agree that it might be worth skipping the fseeko call in the\n> probably-common case where seek_offset is zero. Otherwise I don't\n> see much reason to change what's there.\n>\nTom, if you think it's worth it, I agree with only avoiding syscal fseeko.\n\nregards,\nRanier Vilela", "msg_date": "Mon, 14 Sep 2020 19:57:32 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Simplified version of read_binary_file\n (src/backend/utils/adt/genfile.c)" }, { "msg_contents": "Em sex., 11 de set. de 2020 às 18:43, Ranier Vilela <ranier.vf@gmail.com>\nescreveu:\n\n> Em sex., 11 de set. de 2020 às 17:44, Tom Lane <tgl@sss.pgh.pa.us>\n> escreveu:\n>\n>> Ranier Vilela <ranier.vf@gmail.com> writes:\n>> > New version, with support to read Virtual File (pipe, FIFO and socket).\n>> > With assert, in case, erroneous, of trying to read a pipe, with offset.\n>>\n>> Really, could you do a little more thinking and testing of your own,\n>> rather than expecting the rest of us to point out holes in your thinking?\n>>\n> Yes, I can.\n>\n>\n>> * bytes_to_read == 0 is a legal case.\n>>\n> Ok. Strange call to read a file with zero bytes.\n>\n>\n>> * \"Assert(seek_offset != 0)\" is an equally awful idea.\n>>\n> I was trying to predict the case of reading a Virtual File, with\n> bytes_to_read == -1 and seek_offset == 0,\n> which is bound to fail in fseeko.\n> In any case, 96d1f423f95d it will fail with any Virtual File.\n>\n>\n>>\n>> * Removing the seek code from the negative-bytes_to_read path\n>> is just broken.\n>>\n> Ok.\n>\n>\n>> * The only reason this code is shorter than the previous version is\n>> you took out all the comments explaining what it was doing, and\n>> failed to replace them. This is just as subtle as before, so I\n>> don't find that acceptable.\n>>\n> It was not my intention.\n>\n>\n>>\n>> I do agree that it might be worth skipping the fseeko call in the\n>> probably-common case where seek_offset is zero. Otherwise I don't\n>> see much reason to change what's there.\n>>\n> Well, I think that v3 is a little better, but it’s just my opinion.\n> v3 try to copy directly in the final buffer, which will certainly be a\n> little faster.\n>\nv4 patch, simple benchmark, read binary file with size > 6GB.\n\nPostgreSQL main:\npostgres=# \\timing on\nTiming is on.\npostgres=# select\npg_read_file('c:\\users\\ranier\\downloads\\macOS_Catalina.7z');\nERROR: file length too large\nTime: 3068,459 ms (00:03,068)\npostgres=#\n\nPostgreSQL patched (v4 read_binary_file):\npostgres=# \\timing on\nTiming is on.\npostgres=# select\npg_read_file('c:\\users\\ranier\\downloads\\macOS_Catalina.7z');\nERROR: file length too large\nTime: 701,035 ms\npostgres=#\n\n4.37x faster, very good.\n\nv4 handles pipes very well.\nTested with\nhttps://docs.microsoft.com/en-us/windows/win32/ipc/multithreaded-pipe-server\n\nTerminal one:\nC:\\usr\\src\\tests\\pipes>pipe_server\n\nPipe Server: Main thread awaiting client connection on \\\\.\\pipe\\mynamedpipe\n\nTerminal two:\npostgres=# \\timing on\nTiming is on.\npostgres=# select pg_read_file('\\\\.\\pipe\\mynamedpipe');\n\nTerminal one:\nClient connected, creating a processing thread.\n\nPipe Server: Main thread awaiting client connection on \\\\.\\pipe\\mynamedpipe\nInstanceThread created, receiving and processing messages.\n\nPipe Server: Main thread awaiting client connection on \\\\.\\pipe\\mynamedpipe\nInstanceThread created, receiving and processing messages.\n^C\nC:\\usr\\src\\tests\\pipes>\n\nTerminal two:\npostgres=# select pg_read_file('\\\\.\\pipe\\mynamedpipe');\npg_read_file\n--------------\n\n(1 row)\n\n\nTime: 77267,481 ms (01:17,267)\npostgres=#\n\nregards,\nRanier Vilela", "msg_date": "Tue, 15 Sep 2020 14:43:56 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Simplified version of read_binary_file\n (src/backend/utils/adt/genfile.c)" }, { "msg_contents": "I think you meant _IONBF instead of _IOFBF -- otherwise it's at odds\nwith the comment you add. But what is the justification for that\naddition? I don't see us doing that anywhere else.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 15 Sep 2020 14:54:18 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Simplified version of read_binary_file\n (src/backend/utils/adt/genfile.c)" }, { "msg_contents": "Em ter., 15 de set. de 2020 às 14:54, Alvaro Herrera <\nalvherre@2ndquadrant.com> escreveu:\n\n> I think you meant _IONBF instead of _IOFBF -- otherwise it's at odds\n> with the comment you add. But what is the justification for that\n> addition? I don't see us doing that anywhere else.\n>\nNo.\n_IOFBF *Full buffering:* On output, data is written once the buffer is full\n(or flushed <http://www.cplusplus.com/fflush>). On Input, the buffer is\nfilled when an input operation is requested and the buffer is empty.\n* _IONBF No buffering:* No buffer is used. Each I/O operation is written as\nsoon as possible. In this case, the *buffer* and *size* parameters are\nignored.\n_IONBF ignores buffer and size.\n\nWithout setvbuf, fread uses an internal buffer, default 4096 bytes (OS\ndependent).\nIf fread uses an internal buffer, then it needs a copy to the buffer\nprovided by the function.\nsetvbuf, does the same as read function low level, copies directly to the\nfinal buffer.\n\nregards,\nRanier Vilela\n\nEm ter., 15 de set. de 2020 às 14:54, Alvaro Herrera <alvherre@2ndquadrant.com> escreveu:I think you meant _IONBF instead of _IOFBF -- otherwise it's at odds\nwith the comment you add.  But what is the justification for that\naddition?  I don't see us doing that anywhere else.No.\n_IOFBFFull buffering: On output, data is written once the buffer is full (or flushed). On Input, the buffer is filled when an input operation is requested and the buffer is empty.\n\n\n_IONBF\n\nNo buffering: No buffer is used. Each I/O operation is written as soon as possible. In this case, the buffer and size parameters are ignored. \n_IONBF ignores buffer and size.Without setvbuf, fread uses an internal buffer, default 4096 bytes (OS dependent).If fread uses an internal buffer, then it needs a copy to the buffer provided by the function.setvbuf, does the same as read function low level, copies directly to the final buffer.regards,Ranier Vilela", "msg_date": "Tue, 15 Sep 2020 15:51:10 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Simplified version of read_binary_file\n (src/backend/utils/adt/genfile.c)" } ]
[ { "msg_contents": "Hi,\n\nI've not yet been involved in postgresql's development process, so here's a\nfirst. Please find attached a patch for improving the BT binary search\nspeeds, with accompanying performance data.\n\nv1-0001 adapts _bt_compare and _bt_binsrch* to make use of static\nproperties of L&Y-style nbtree indexes to speed up finding an initial\nposition in the nbtee.\n\nI alter the logic from _bt_compare to accept a 'start-comparing-at-column'\nargument, and to also return which column the comparison result came from.\nThis allows us to keep track of which columns we've already checked for\nequality, and when getting deeper into the index this allows us to skip\nchecking the already equal key columns.\n\nSpecifically, when binary-searching through a page, we keep track of which\ncolumn was checked for the high-key, and which for the low-key. The first\ncolumn of these that is not yet equal will be used for the next comparison.\nAny columns before this column must be equal, as both the high- and the\nlow-keys in that page have already been validated as having an equal\nprefix. The column number is then passed on through the insertion key,\nallowing the optimization to be used in the climbing of the nbtree index.\n\nv1-0001 will be especially performant in nbtree indexes with a relatively\nlow initial cardinality and high compare cost. My own performance testing\nwas done on a laptop (4c/8t), after first getting it warm with other\nbenchmarks & compilations, so the results are a bit unstable.\n\nWhile testing this I also noticed that there were a lot of pipeline stalls\naround the arguments and results of _bt_compare in the hot loops of\n_bt_binsrch* where the new functionality would be used, so I've moved the\ncore logic of _bt_compare to a static inline function _bt_compare_inline,\nwhich helped the code to go from a 2% TPS decrease for single-column\nindexes to ~ 8% TPS increase for an insert-only workload, and for 3-column\ntext all-collated indexes a TPS increase of 20% on my system. This also\nallowed me to keep the signature of _bt_compare the same as it was,\nlimiting the scope of the changes to only the named functions.\n\nFinally, this could be a great start on prefix truncation for btree\nindexes, though that is _not_ the goal of this patch. This patch skips, but\ndoes not truncate, the common prefix.\n\nKind regards,\n\nMatthias van de Meent\n\nP.S. One more thing I noticed in benchmarking is that a significant part of\nthe costs of non-default collations is in looking up the collation twice in\nthe collation cache. My guess from flame graphs is that there could be a\nlarge throughput increase for short strings if the collation lookup from\nlc_collate_is_c() in varstr_cmp could be reused in the subsequent call to\npg_newlocale_from_collation()", "msg_date": "Fri, 11 Sep 2020 16:57:36 +0200", "msg_from": "Matthias van de Meent <boekewurm+postgres@gmail.com>", "msg_from_op": true, "msg_subject": "[patch] _bt_binsrch* improvements - equal-prefix-skip binary search" }, { "msg_contents": "On Fri, Sep 11, 2020 at 7:57 AM Matthias van de Meent\n<boekewurm+postgres@gmail.com> wrote:\n> I've not yet been involved in postgresql's development process, so here's a first. Please find attached a patch for improving the BT binary search speeds, with accompanying performance data.\n>\n> v1-0001 adapts _bt_compare and _bt_binsrch* to make use of static properties of L&Y-style nbtree indexes to speed up finding an initial position in the nbtee.\n\nAre you familiar with this thread?\n\nhttps://www.postgresql.org/message-id/CAH2-Wzn_NAyK4pR0HRWO0StwHmxjP5qyu+X8vppt030XpqrO6w@mail.gmail.com\n\nI wrote a patch that implemented the same idea, which is sometimes\ncalled dynamic prefix truncation. I found some very subtle problems\nwith it, though. Concurrent page deletions could occur, which could\ncause a scan that skips a prefix to miss that the page it landed on\ndoesn't have the same common prefix anymore.\n\n> there could be a large throughput increase for short strings if the collation lookup from lc_collate_is_c() in varstr_cmp could be reused in the subsequent call to pg_newlocale_from_collation()\n\nI noticed that myself recently.\n\n--\nPeter Geoghegan\n\n\n", "msg_date": "Fri, 11 Sep 2020 10:41:01 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: [patch] _bt_binsrch* improvements - equal-prefix-skip binary\n search" }, { "msg_contents": "On Fri, 11 Sep 2020 at 19:41, Peter Geoghegan <pg@bowt.ie> wrote:\n>\n> Are you familiar with this thread?\n>\n>\nhttps://www.postgresql.org/message-id/CAH2-Wzn_NAyK4pR0HRWO0StwHmxjP5qyu+X8vppt030XpqrO6w@mail.gmail.com\n>\n> I wrote a patch that implemented the same idea, which is sometimes\n> called dynamic prefix truncation. I found some very subtle problems\n> with it, though. Concurrent page deletions could occur, which could\n> cause a scan that skips a prefix to miss that the page it landed on\n> doesn't have the same common prefix anymore.\n\nThank you for pointing me to that thread, I was not yet familiar with it.\nIt took me some time to get familiar with the Lanin and Shasha [0] paper,\nbut the concerns regarding concurrent page deletion are indeed problematic\nfor algorithmic prefix truncation, and do make it near impossible to use\nalgorithmic prefix truncation without resetting the accumulated prefix\nevery page.\n\nAt that, I will retract this current patch, and (unless someone's already\nworking on it) start research on implementing physical prefix truncation\nthrough deduplicating the prefix shared with a page's highkey. This would\nlikely work fine for inner nodes (there are still flag bits left unused,\nand the concerns related to deduplication of equal-but-distinct values do\nnot apply there), though I'm uncertain about the ability to truncate\nduplicate prefixes in leaf nodes as it is basically prefix deduplication\nwith the same problems attached as 'normal' deduplication.\n\nThanks,\n\nMatthias van de Meent\n\n[0] https://archive.org/stream/symmetricconcurr00lani\n\n\nOn Fri, 11 Sep 2020 at 19:41, Peter Geoghegan <pg@bowt.ie> wrote:\n>\n> Are you familiar with this thread?\n>\n> https://www.postgresql.org/message-id/CAH2-Wzn_NAyK4pR0HRWO0StwHmxjP5qyu+X8vppt030XpqrO6w@mail.gmail.com\n>\n> I wrote a patch that implemented the same idea, which is sometimes\n> called dynamic prefix truncation. I found some very subtle problems\n> with it, though. Concurrent page deletions could occur, which could\n> cause a scan that skips a prefix to miss that the page it landed on\n> doesn't have the same common prefix anymore.\nThank you for pointing me to that thread, I was not yet familiar with it. It took me some time to get familiar with the Lanin and Shasha [0] paper, but the concerns regarding concurrent page deletion are indeed problematic for algorithmic prefix truncation, and do make it near impossible to use algorithmic prefix truncation without resetting the accumulated prefix every page.At that, I will retract this current patch, and (unless someone's already working on it) start research on implementing physical prefix truncation through deduplicating the prefix shared with a page's highkey. This would likely work fine for inner nodes (there are still flag bits left unused, and the concerns related to deduplication of equal-but-distinct values do not apply there), though I'm uncertain about the ability to truncate duplicate prefixes in leaf nodes as it is basically prefix deduplication with the same problems attached as 'normal' deduplication.Thanks,Matthias van de Meent[0] https://archive.org/stream/symmetricconcurr00lani", "msg_date": "Tue, 15 Sep 2020 11:03:14 +0200", "msg_from": "Matthias van de Meent <boekewurm+postgres@gmail.com>", "msg_from_op": true, "msg_subject": "Re: [patch] _bt_binsrch* improvements - equal-prefix-skip binary\n search" } ]
[ { "msg_contents": "Today we have pg_read_file() and pg_read_binary_file(), which mostly\ncorrespond to COPY from a file, but reads a whole (or parts but based on\nbytes) into a single value rather than rows.\n\nWould it make sense to have a pg_execute_program() that corresponds to COPY\nFROM PROGRAM? This would obviously have the same permissions restrictions\nas COPY FROM PROGRAM.\n\nThe usecase would be to for example execute a command that returns json\nformat output, which could then be parsed and processed as part of a query.\nToday, COPY FROM PROGRAM cannot do this, as we can't read a multiline json\nvalue with COPY.\n\nThoughts?\n\n//Magnus\n\nToday we have pg_read_file() and pg_read_binary_file(), which mostly correspond to COPY from a file, but reads a whole (or parts but based on bytes) into a single value rather than rows.Would it make sense to have a pg_execute_program() that corresponds to COPY FROM PROGRAM? This would obviously have the same permissions restrictions as COPY FROM PROGRAM.The usecase would be to for example execute a command that returns json format output, which could then be parsed and processed as part of a query. Today, COPY FROM PROGRAM cannot do this, as we can't read a multiline json value with COPY.Thoughts?//Magnus", "msg_date": "Sat, 12 Sep 2020 15:12:02 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": true, "msg_subject": "Function to execute a program" }, { "msg_contents": "Magnus Hagander <magnus@hagander.net> writes:\n> Would it make sense to have a pg_execute_program() that corresponds to COPY\n> FROM PROGRAM? This would obviously have the same permissions restrictions\n> as COPY FROM PROGRAM.\n> The usecase would be to for example execute a command that returns json\n> format output, which could then be parsed and processed as part of a query.\n> Today, COPY FROM PROGRAM cannot do this, as we can't read a multiline json\n> value with COPY.\n\ncopy ... from program 'random_json_producer | tr \"\\n\\t\" \" \"';\n\nI don't necessarily object to providing such a function to make it\neasier, but it's not the case that you can't have the functionality\ntoday.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 12 Sep 2020 11:06:00 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Function to execute a program" }, { "msg_contents": "On Sat, Sep 12, 2020 at 5:06 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Magnus Hagander <magnus@hagander.net> writes:\n> > Would it make sense to have a pg_execute_program() that corresponds to\n> COPY\n> > FROM PROGRAM? This would obviously have the same permissions restrictions\n> > as COPY FROM PROGRAM.\n> > The usecase would be to for example execute a command that returns json\n> > format output, which could then be parsed and processed as part of a\n> query.\n> > Today, COPY FROM PROGRAM cannot do this, as we can't read a multiline\n> json\n> > value with COPY.\n>\n> copy ... from program 'random_json_producer | tr \"\\n\\t\" \" \"';\n>\n> I don't necessarily object to providing such a function to make it\n> easier, but it's not the case that you can't have the functionality\n> today.\n>\n\n\"tr\" is not typically available on Windows, for one :)\n\nBut yes, assuming tr is available, it is true that you can. (And you can\nperhaps find something else to pipe it through on Windows). Of course, you\nstill can't use it in a query, since COPY can only target a table :)\nIndependently of something like this it would be nice to be able to target\nsay a CTE with COPY, but that's kan entirely different 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 Sat, Sep 12, 2020 at 5:06 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:Magnus Hagander <magnus@hagander.net> writes:\n> Would it make sense to have a pg_execute_program() that corresponds to COPY\n> FROM PROGRAM? This would obviously have the same permissions restrictions\n> as COPY FROM PROGRAM.\n> The usecase would be to for example execute a command that returns json\n> format output, which could then be parsed and processed as part of a query.\n> Today, COPY FROM PROGRAM cannot do this, as we can't read a multiline json\n> value with COPY.\n\ncopy ... from program 'random_json_producer | tr \"\\n\\t\" \"  \"';\n\nI don't necessarily object to providing such a function to make it\neasier, but it's not the case that you can't have the functionality\ntoday.\"tr\" is not typically available on Windows, for one :)But yes, assuming tr is available, it is true that you can. (And you can perhaps find something else to pipe it through on Windows). Of course, you still can't use it in a query, since COPY can only target a table :) Independently of something like this it would be nice to be able to target say a CTE with COPY, but that's kan entirely different topic.--  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Sat, 12 Sep 2020 17:11:29 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": true, "msg_subject": "Re: Function to execute a program" }, { "msg_contents": "\nOn 9/12/20 11:11 AM, Magnus Hagander wrote:\n>\n>\n> On Sat, Sep 12, 2020 at 5:06 PM Tom Lane <tgl@sss.pgh.pa.us\n> <mailto:tgl@sss.pgh.pa.us>> wrote:\n>\n> Magnus Hagander <magnus@hagander.net <mailto:magnus@hagander.net>>\n> writes:\n> > Would it make sense to have a pg_execute_program() that\n> corresponds to COPY\n> > FROM PROGRAM? This would obviously have the same permissions\n> restrictions\n> > as COPY FROM PROGRAM.\n> > The usecase would be to for example execute a command that\n> returns json\n> > format output, which could then be parsed and processed as part\n> of a query.\n> > Today, COPY FROM PROGRAM cannot do this, as we can't read a\n> multiline json\n> > value with COPY.\n>\n> copy ... from program 'random_json_producer | tr \"\\n\\t\" \"  \"';\n>\n> I don't necessarily object to providing such a function to make it\n> easier, but it's not the case that you can't have the functionality\n> today.\n>\n>\n> \"tr\" is not typically available on Windows, for one :)\n>\n> But yes, assuming tr is available, it is true that you can. (And you\n> can perhaps find something else to pipe it through on Windows). Of\n> course, you still can't use it in a query, since COPY can only target\n> a table :) Independently of something like this it would be nice to be\n> able to target say a CTE with COPY, but that's kan entirely different\n> topic.\n>\n>\n\nA more robust recipe  would use \"jq -c\" as the filter. And it's\navailable on Windows via chocolatey.\n\n\nI don't have a strong opinion on the suggested facility. Presumably you\ncan construct a function that runs COPY into a temp table and then\nreturns the results. But maybe that's more work than we should require\nusers to perform.\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": "Sat, 12 Sep 2020 11:36:39 -0400", "msg_from": "Andrew Dunstan <andrew.dunstan@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Function to execute a program" }, { "msg_contents": "Greetings,\n\n* Magnus Hagander (magnus@hagander.net) wrote:\n> Would it make sense to have a pg_execute_program() that corresponds to COPY\n> FROM PROGRAM? This would obviously have the same permissions restrictions\n> as COPY FROM PROGRAM.\n\nEh, perhaps.\n\n> The usecase would be to for example execute a command that returns json\n> format output, which could then be parsed and processed as part of a query.\n> Today, COPY FROM PROGRAM cannot do this, as we can't read a multiline json\n> value with COPY.\n\nI'd rather come up with a way to import this kind of object into PG by\nusing COPY rather than adding a different way to pull them in.\n\nIn the \"this is a crazy idea\" category- have a way to specify an input\nfunction to COPY, or a target data type (and then use it's input\nfunction) to which COPY just keeps feeding bytes until the function\ncomes back with \"ok, I got a value to return\" or something.\n\nWould be really neat to have a way to COPY in a JSON, XML, or whatever\neven if it's multi-line and even if it has multiple objects (ie: 10\ncomplete JSON documents in a single file would become 10 rows of jsonb).\n\nThanks,\n\nStephen", "msg_date": "Mon, 14 Sep 2020 10:33:01 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Function to execute a program" }, { "msg_contents": "Stephen Frost <sfrost@snowman.net> writes:\n> * Magnus Hagander (magnus@hagander.net) wrote:\n>> Would it make sense to have a pg_execute_program() that corresponds to COPY\n>> FROM PROGRAM? This would obviously have the same permissions restrictions\n>> as COPY FROM PROGRAM.\n\n> I'd rather come up with a way to import this kind of object into PG by\n> using COPY rather than adding a different way to pull them in.\n\nI'm not for overloading COPY to try to make it handle every data import\nuse-case. The issue here AIUI is that Magnus wants the program output\nto be read as an uninterpreted blob (which he'll then try to convert to\njsonb or whatever, but that's not the concern of the import code). This\nis exactly antithetical to COPY's mission of reading some rows that are\nmade up of some columns and putting the result into a table.\n\nYeah, we could no doubt add some functionality to disable all the\nrow-splitting and column-splitting and associated escaping logic,\nbut that's going to make COPY slower and more complicated. And it\nstill doesn't address wanting to use the result directly in a query\ninstead of sticking it into a table.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 14 Sep 2020 10:45:31 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Function to execute a program" }, { "msg_contents": "Greetings.\n\n* Tom Lane (tgl@sss.pgh.pa.us) wrote:\n> Stephen Frost <sfrost@snowman.net> writes:\n> > * Magnus Hagander (magnus@hagander.net) wrote:\n> >> Would it make sense to have a pg_execute_program() that corresponds to COPY\n> >> FROM PROGRAM? This would obviously have the same permissions restrictions\n> >> as COPY FROM PROGRAM.\n> \n> > I'd rather come up with a way to import this kind of object into PG by\n> > using COPY rather than adding a different way to pull them in.\n> \n> I'm not for overloading COPY to try to make it handle every data import\n> use-case. The issue here AIUI is that Magnus wants the program output\n> to be read as an uninterpreted blob (which he'll then try to convert to\n> jsonb or whatever, but that's not the concern of the import code). This\n> is exactly antithetical to COPY's mission of reading some rows that are\n> made up of some columns and putting the result into a table.\n\nI don't really think there's anything inherent in the fact that \"COPY\"\ntoday only has one way to handle data that the user wants to import that\nit should be required to always operate in that manner.\n\nAs for slowing down the current method- I don't think that we'd\nimplement such a change as just a modification to the existing optimized\nparsing code as that just wouldn't make any sense and would slow COPY\ndown for this use-case, but having a COPY command that's able to work in\na few different modes when it comes to importing data seems like it\ncould be sensible, fast, and clear to users.\n\nOne could imagine creating some other top-level command to handle more\ncomplex import cases than what COPY does today but I don't actually\nthink that'd be an improvment.\n\n> Yeah, we could no doubt add some functionality to disable all the\n> row-splitting and column-splitting and associated escaping logic,\n> but that's going to make COPY slower and more complicated. And it\n> still doesn't address wanting to use the result directly in a query\n> instead of sticking it into a table.\n\nThe way that's handled for the cases that COPY does work with today is\nfile_fdw. Ideally, we'd do the same here.\n\nUltimately, COPY absolutely *is* our general data import tool- it's just\nthat today we push some of the work to make things 'fit' on the user and\nthat ends up with pain points like exactly what Magnus has pointed out\nhere. We should be looking to improve that situation, and I don't\nreally care for the solution to that being \"create some random other new\nthing for data import that users then have to know exists and learn how\nto use\".\n\nThanks,\n\nStephen", "msg_date": "Mon, 14 Sep 2020 10:57:05 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Function to execute a program" } ]
[ { "msg_contents": "Hi\n\nI try to solve issue\nhttps://stackoverflow.com/questions/63864906/plpgsql-parse-json-in-parameter-and-compose-json-out-parameter\nwith JSONPath and I have a problem to get index of some value in array. Is\nit possible with JSONPath?\n\nRegards\n\nPavel\n\nHiI try to solve issue https://stackoverflow.com/questions/63864906/plpgsql-parse-json-in-parameter-and-compose-json-out-parameter with JSONPath and I have a problem to get index of some value in array. Is it possible with JSONPath?RegardsPavel", "msg_date": "Sun, 13 Sep 2020 08:22:14 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": true, "msg_subject": "How to get position in array with JSONPath" } ]
[ { "msg_contents": "While trying to understand a recent buildfarm failure [1], I got annoyed\nby the fact that a walsender exposes its last SQL command in\npg_stat_activity even when that was a long time ago and what it's been\ndoing since then is replication commands. This leads to *totally*\nmisleading reports, for instance in [1] we read\n\n2020-09-13 19:10:09.632 CEST [5f5e526d.242415:4] LOG: server process (PID 2368853) was terminated by signal 11: Segmentation fault\n2020-09-13 19:10:09.632 CEST [5f5e526d.242415:5] DETAIL: Failed process was running: SELECT pg_catalog.set_config('search_path', '', false);\n\neven though the process's own log messages paint a much better picture of\nreality:\n\n2020-09-13 19:10:07.302 CEST [5f5e526f.242555:1] LOG: connection received: host=[local]\n2020-09-13 19:10:07.303 CEST [5f5e526f.242555:2] LOG: replication connection authorized: user=bf application_name=sub2\n2020-09-13 19:10:07.303 CEST [5f5e526f.242555:3] LOG: statement: SELECT pg_catalog.set_config('search_path', '', false);\n2020-09-13 19:10:07.334 CEST [5f5e526f.242555:4] LOG: received replication command: IDENTIFY_SYSTEM\n2020-09-13 19:10:07.335 CEST [5f5e526f.242555:5] LOG: received replication command: START_REPLICATION SLOT \"sub2\" LOGICAL 0/0 (proto_version '2', publication_names '\"pub2\"')\n2020-09-13 19:10:07.335 CEST [5f5e526f.242555:6] LOG: starting logical decoding for slot \"sub2\"\n2020-09-13 19:10:07.335 CEST [5f5e526f.242555:7] DETAIL: Streaming transactions committing after 0/159EB38, reading WAL from 0/159EB00.\n2020-09-13 19:10:07.335 CEST [5f5e526f.242555:8] LOG: logical decoding found consistent point at 0/159EB00\n2020-09-13 19:10:07.335 CEST [5f5e526f.242555:9] DETAIL: There are no running transactions.\n\nI think that walsenders ought to report their current replication command\nas though it were a SQL command. They oughta set debug_query_string, too.\n\nWhile trying to fix this, I also observed that exec_replication_command\nfails to clean up the temp context it made for parsing the command string,\nif that turns out to be a SQL command. This very accidentally fails to\nlead to a long-term memory leak, because that context will be a child of\nMessageContext so it'll be cleaned out in the next iteration of\nPostgresMain's main loop. But it's still unacceptably sloppy coding\nIMHO, and it's closely related to a lot of other randomness in the\nfunction; it'd be better to have a separate early-exit path for SQL\ncommands.\n\nAttached find a proposed fix for these things.\n\nWhat I'd really like to do is adjust pgstat_report_activity so that\ncallers are *required* to provide some kind of command string when\ntransitioning into STATE_RUNNING state, ie something like\n\n\tAssert(state == STATE_RUNNING ? cmd_str != NULL : cmd_str == NULL);\n\nHowever, before we could do that, we'd have to clean up the rat's nest\nof seemingly-inserted-with-the-aid-of-a-dartboard pgstat_report_activity\ncalls in replication/logical/worker.c. I couldn't make heads or tails\nof what is going on there, so I did not try.\n\nBTW, while I didn't change it here, isn't the second\nSnapBuildClearExportedSnapshot call in exec_replication_command just\nuseless? We already did that before parsing the command.\n\n\t\t\tregards, tom lane\n\n[1] https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=idiacanthus&dt=2020-09-13%2016%3A54%3A03", "msg_date": "Sun, 13 Sep 2020 15:47:51 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Gripes about walsender command processing" }, { "msg_contents": "I wrote:\n> I think that walsenders ought to report their current replication command\n> as though it were a SQL command. They oughta set debug_query_string, too.\n\nI also notice that a walsender does not maintain its ps status:\n\npostgres 921109 100 0.0 32568 11880 ? Rs 18:57 0:51 postgres: publisher: walsender postgres [local] idle\n\nI don't mind if we decide we don't need to reflect the walsender's\ntrue activity, but let's not have it showing an outright lie.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 13 Sep 2020 19:00:26 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Gripes about walsender command processing" }, { "msg_contents": "On Sun, Sep 13, 2020 at 03:47:51PM -0400, Tom Lane wrote:\n> While trying to fix this, I also observed that exec_replication_command\n> fails to clean up the temp context it made for parsing the command string,\n> if that turns out to be a SQL command. This very accidentally fails to\n> lead to a long-term memory leak, because that context will be a child of\n> MessageContext so it'll be cleaned out in the next iteration of\n> PostgresMain's main loop. But it's still unacceptably sloppy coding\n> IMHO, and it's closely related to a lot of other randomness in the\n> function; it'd be better to have a separate early-exit path for SQL\n> commands.\n\nLooks fine seen from here. +1.\n\n> What I'd really like to do is adjust pgstat_report_activity so that\n> callers are *required* to provide some kind of command string when\n> transitioning into STATE_RUNNING state, ie something like\n> \n> \tAssert(state == STATE_RUNNING ? cmd_str != NULL : cmd_str == NULL);\n> \n> However, before we could do that, we'd have to clean up the rat's nest\n> of seemingly-inserted-with-the-aid-of-a-dartboard pgstat_report_activity\n> calls in replication/logical/worker.c. I couldn't make heads or tails\n> of what is going on there, so I did not try.\n\nFor this one, I don't actually agree. For now the state and the query\nstring, actually the activity string, are completely independent. So\nexternal modules like bgworkers can mix the state enum and the\nactivity string as they wish. I think that this flexibility is useful\nto keep.\n\n> BTW, while I didn't change it here, isn't the second\n> SnapBuildClearExportedSnapshot call in exec_replication_command just\n> useless? We already did that before parsing the command.\n\nIndeed.\n--\nMichael", "msg_date": "Mon, 14 Sep 2020 17:04:54 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Gripes about walsender command processing" }, { "msg_contents": "Michael Paquier <michael@paquier.xyz> writes:\n> On Sun, Sep 13, 2020 at 03:47:51PM -0400, Tom Lane wrote:\n>> While trying to fix this, I also observed that exec_replication_command\n>> fails to clean up the temp context it made for parsing the command string,\n>> if that turns out to be a SQL command. This very accidentally fails to\n>> lead to a long-term memory leak, because that context will be a child of\n>> MessageContext so it'll be cleaned out in the next iteration of\n>> PostgresMain's main loop. But it's still unacceptably sloppy coding\n>> IMHO, and it's closely related to a lot of other randomness in the\n>> function; it'd be better to have a separate early-exit path for SQL\n>> commands.\n\n> Looks fine seen from here. +1.\n\nPushed, thanks for looking.\n\n>> What I'd really like to do is adjust pgstat_report_activity so that\n>> callers are *required* to provide some kind of command string when\n>> transitioning into STATE_RUNNING state, ie something like\n>> Assert(state == STATE_RUNNING ? cmd_str != NULL : cmd_str == NULL);\n\n> For this one, I don't actually agree. For now the state and the query\n> string, actually the activity string, are completely independent. So\n> external modules like bgworkers can mix the state enum and the\n> activity string as they wish. I think that this flexibility is useful\n> to keep.\n\nMeh ... but I'm not excited enough about the point to argue.\n\nI looked into the other point about ps status always claiming the\nwalsender is \"idle\". This turns out to be something PostgresMain\ndoes automatically, so unless we want to uglify that logic, we have\nto make walsenders set the field honestly. So I propose the attached.\n(Is there a better way to get the name of a replication command?\nI didn't look very hard for one.)\n\n\t\t\tregards, tom lane", "msg_date": "Mon, 14 Sep 2020 12:51:39 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Gripes about walsender command processing" }, { "msg_contents": "On Mon, Sep 14, 2020 at 12:51:39PM -0400, Tom Lane wrote:\n> I looked into the other point about ps status always claiming the\n> walsender is \"idle\". This turns out to be something PostgresMain\n> does automatically, so unless we want to uglify that logic, we have\n> to make walsenders set the field honestly. So I propose the attached.\n> (Is there a better way to get the name of a replication command?\n> I didn't look very hard for one.)\n\nWouldn't that just be in cmdtaglist.h, but extended for nodes used for\nreplication commands? Then you could just call CreateCommandTag() to\nget the command string to print as postgres.c does. There is already\none for repslot drop, in some way. This would have the advantage to\njust call once set_ps_display() before the switch split.\n--\nMichael", "msg_date": "Tue, 15 Sep 2020 12:22:15 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Gripes about walsender command processing" }, { "msg_contents": "Michael Paquier <michael@paquier.xyz> writes:\n> On Mon, Sep 14, 2020 at 12:51:39PM -0400, Tom Lane wrote:\n>> (Is there a better way to get the name of a replication command?\n>> I didn't look very hard for one.)\n\n> Wouldn't that just be in cmdtaglist.h, but extended for nodes used for\n> replication commands? Then you could just call CreateCommandTag() to\n> get the command string to print as postgres.c does. There is already\n> one for repslot drop, in some way. This would have the advantage to\n> just call once set_ps_display() before the switch split.\n\nMmm, not sure whether having CreateCommandTag know about replication\ncommands is a good thing or not. We certainly could do it like that,\nsince there's only one namespace of NodeTag values, but conceptually\nit feels a bit weird to me. There's a lot of other infrastructure\nfor SQL command nodes that we're surely never going to build out for\nreplication commands, so should we do it in CreateCommandTag?\n\nAnybody else have an opinion about it?\n\n(I don't quite follow your comment about repslot drop, btw.)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 14 Sep 2020 23:34:44 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Gripes about walsender command processing" }, { "msg_contents": "On Mon, Sep 14, 2020 at 11:34:44PM -0400, Tom Lane wrote:\n> (I don't quite follow your comment about repslot drop, btw.)\n\nThere is already a command tag equivalent to DROP_REPLICATION_SLOT:\n$ git grep REPLICATION -- */cmdtaglist.h\nsrc/include/tcop/cmdtaglist.h:PG_CMDTAG(CMDTAG_DROP_REPLICATION_SLOT,\n\"DROP REPLICATION SLOT\", false, false, false)\n--\nMichael", "msg_date": "Tue, 15 Sep 2020 14:06:55 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Gripes about walsender command processing" }, { "msg_contents": "Michael Paquier <michael@paquier.xyz> writes:\n> On Mon, Sep 14, 2020 at 11:34:44PM -0400, Tom Lane wrote:\n>> (I don't quite follow your comment about repslot drop, btw.)\n\n> There is already a command tag equivalent to DROP_REPLICATION_SLOT:\n> $ git grep REPLICATION -- */cmdtaglist.h\n> src/include/tcop/cmdtaglist.h:PG_CMDTAG(CMDTAG_DROP_REPLICATION_SLOT,\n> \"DROP REPLICATION SLOT\", false, false, false)\n\n[ blink ... ] So why is it that DropReplicationSlot does\n\n\tSetQueryCompletion(&qc, CMDTAG_DROP_REPLICATION_SLOT, 0);\n\tEndCommand(&qc, DestRemote, false);\n\nwhen the caller will immediately after that do\n\n\tSetQueryCompletion(&qc, CMDTAG_SELECT, 0);\n\tEndCommand(&qc, DestRemote, true);\n\nStartLogicalReplication has a similar weirdness.\nThe more I look at this code, the more broken it seems.\n\nAnyway, independently of whether walsender should be sending multiple\ncommand-complete messages, I don't think I really approve of including\nreplication commands in the CommandTag enum. It still seems like a\ntype pun. However, it looks like we'd have to duplicate\nSetQueryCompletion/EndCommand if we don't want to do that, so maybe\nI'd better just hold my nose and do it that way.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 15 Sep 2020 14:48:55 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Gripes about walsender command processing" }, { "msg_contents": "On 2020-Sep-15, Tom Lane wrote:\n\n> [ blink ... ] So why is it that DropReplicationSlot does\n> \n> \tSetQueryCompletion(&qc, CMDTAG_DROP_REPLICATION_SLOT, 0);\n> \tEndCommand(&qc, DestRemote, false);\n> \n> when the caller will immediately after that do\n> \n> \tSetQueryCompletion(&qc, CMDTAG_SELECT, 0);\n> \tEndCommand(&qc, DestRemote, true);\n> \n> StartLogicalReplication has a similar weirdness.\n> The more I look at this code, the more broken it seems.\n\nI overlooked this in 2f9661311b83. From this perspective, I agree it\nlooks wrong. We still have to send *some* completion tag (the 'C'\nmessage), but maybe we can invent a separate entry point in dest.c for\nthat -- EndReplicationCommand() or some such -- that takes values from a\nseparate enum?\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 15 Sep 2020 18:33:16 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Gripes about walsender command processing" }, { "msg_contents": "On 2020-Sep-15, Alvaro Herrera wrote:\n\n> I overlooked this in 2f9661311b83. From this perspective, I agree it\n> looks wrong. We still have to send *some* completion tag (the 'C'\n> message), but maybe we can invent a separate entry point in dest.c for\n> that -- EndReplicationCommand() or some such -- that takes values from a\n> separate enum?\n\nIt seems simpler than that actually; we don't need to build a lot of\ninfrastructure.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Wed, 16 Sep 2020 13:36:33 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Gripes about walsender command processing" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> On 2020-Sep-15, Alvaro Herrera wrote:\n>> I overlooked this in 2f9661311b83. From this perspective, I agree it\n>> looks wrong. We still have to send *some* completion tag (the 'C'\n>> message), but maybe we can invent a separate entry point in dest.c for\n>> that -- EndReplicationCommand() or some such -- that takes values from a\n>> separate enum?\n\n> It seems simpler than that actually; we don't need to build a lot of\n> infrastructure.\n\nThis looks moderately reasonable to me. However, with the process\ntitle reporting I want to add, we're going to end up with a switch\nthat looks like\n\n \t\tcase T_IdentifySystemCmd:\n+\t\t\tset_ps_display(\"IDENTIFY_SYSTEM\");\n \t\t\tIdentifySystem();\n+\t\t\tEndReplicationCommand(\"IDENTIFY_SYSTEM\");\n \t\t\tbreak;\n \n \t\tcase T_BaseBackupCmd:\n+\t\t\tset_ps_display(\"BASE_BACKUP\");\n \t\t\tPreventInTransactionBlock(true, \"BASE_BACKUP\");\n \t\t\tSendBaseBackup((BaseBackupCmd *) cmd_node);\n+\t\t\tEndReplicationCommand(\"BASE_BACKUP\");\n \t\t\tbreak;\n\nwhich is starting to look a bit repetitive and copy-pasteo-prone.\nI don't see an easy way to improve on it though. The only obvious\nalternative would be to put another switch before the main one that\njust fills a \"const char *cmdtag\" variable, but that seems ugly.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 16 Sep 2020 12:44:29 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Gripes about walsender command processing" }, { "msg_contents": "On 2020-Sep-16, Tom Lane wrote:\n\n> This looks moderately reasonable to me. However, with the process\n> title reporting I want to add, we're going to end up with a switch\n> that looks like\n> \n> \t\tcase T_IdentifySystemCmd:\n> +\t\t\tset_ps_display(\"IDENTIFY_SYSTEM\");\n> \t\t\tIdentifySystem();\n> +\t\t\tEndReplicationCommand(\"IDENTIFY_SYSTEM\");\n> \t\t\tbreak;\n> \n> \t\tcase T_BaseBackupCmd:\n> +\t\t\tset_ps_display(\"BASE_BACKUP\");\n> \t\t\tPreventInTransactionBlock(true, \"BASE_BACKUP\");\n> \t\t\tSendBaseBackup((BaseBackupCmd *) cmd_node);\n> +\t\t\tEndReplicationCommand(\"BASE_BACKUP\");\n> \t\t\tbreak;\n> \n> which is starting to look a bit repetitive and copy-pasteo-prone.\n\nAgreed.\n\n> I don't see an easy way to improve on it though. The only obvious\n> alternative would be to put another switch before the main one that\n> just fills a \"const char *cmdtag\" variable, but that seems ugly.\n\nThe alternative of doing the assignment in each case of the same switch\ndoes not look too terrible:\n\n \t\tcase T_IdentifySystemCmd:\n+\t\t\tcmdtag = \"IDENTIFY_SYSTEM\";\n+\t\t\tset_ps_display(cmdtag);\n \t\t\tIdentifySystem();\n+\t\t\tEndReplicationCommand(cmdtag);\n \t\t\tbreak;\n \n \t\tcase T_BaseBackupCmd:\n+\t\t\tcmdtag = \"BASE_BACKUP\";\n+\t\t\tset_ps_display(cmdtag);\n \t\t\tPreventInTransactionBlock(true, cmdtag);\n \t\t\tSendBaseBackup((BaseBackupCmd *) cmd_node);\n+\t\t\tEndReplicationCommand(cmdtag);\n \t\t\tbreak;\n\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 16 Sep 2020 19:14:22 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Gripes about walsender command processing" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> On 2020-Sep-16, Tom Lane wrote:\n>> I don't see an easy way to improve on it though. The only obvious\n>> alternative would be to put another switch before the main one that\n>> just fills a \"const char *cmdtag\" variable, but that seems ugly.\n\n> The alternative of doing the assignment in each case of the same switch\n> does not look too terrible:\n\n> \t\tcase T_IdentifySystemCmd:\n> +\t\t\tcmdtag = \"IDENTIFY_SYSTEM\";\n> +\t\t\tset_ps_display(cmdtag);\n> \t\t\tIdentifySystem();\n> +\t\t\tEndReplicationCommand(cmdtag);\n> \t\t\tbreak;\n \n> \t\tcase T_BaseBackupCmd:\n> +\t\t\tcmdtag = \"BASE_BACKUP\";\n> +\t\t\tset_ps_display(cmdtag);\n> \t\t\tPreventInTransactionBlock(true, cmdtag);\n> \t\t\tSendBaseBackup((BaseBackupCmd *) cmd_node);\n> +\t\t\tEndReplicationCommand(cmdtag);\n> \t\t\tbreak;\n\nYeah, that works for me. It doesn't allow for having just one\nset_ps_display() call ahead of the switch, but that isn't that\nbig a loss. We cannot merge the EndReplicationCommand calls to\nafter the switch, because some of the cases don't want one here;\nso that partial duplication is inescapable.\n\nNote that your changes need to be backpatched into v13,\nbecause AFAICS this code is violating the FE/BE protocol\nright now --- it's just luck that libpq isn't moaning\nabout extra CommandComplete messages. But I don't think\nwe want to change the ps title behavior in v13 at this\nlate date, so that part should be HEAD-only.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 16 Sep 2020 18:21:08 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Gripes about walsender command processing" }, { "msg_contents": "On 2020-Sep-16, Tom Lane wrote:\n\n> Yeah, that works for me. It doesn't allow for having just one\n> set_ps_display() call ahead of the switch, but that isn't that\n> big a loss. We cannot merge the EndReplicationCommand calls to\n> after the switch, because some of the cases don't want one here;\n> so that partial duplication is inescapable.\n\nRight.\n\n> Note that your changes need to be backpatched into v13,\n> because AFAICS this code is violating the FE/BE protocol\n> right now --- it's just luck that libpq isn't moaning\n> about extra CommandComplete messages. But I don't think\n> we want to change the ps title behavior in v13 at this\n> late date, so that part should be HEAD-only.\n\nOk, will do.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 16 Sep 2020 19:46:14 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Gripes about walsender command processing" }, { "msg_contents": "On 2020-Sep-16, Tom Lane wrote:\n\n> Note that your changes need to be backpatched into v13,\n> because AFAICS this code is violating the FE/BE protocol\n> right now --- it's just luck that libpq isn't moaning\n> about extra CommandComplete messages. But I don't think\n> we want to change the ps title behavior in v13 at this\n> late date, so that part should be HEAD-only.\n\nI pushed to 13, but it's because of the removal of the command tag; the\nduplicate tags we've been sending since 9.3. ¯\\_(ツ)_/¯\n\n-- \nÁlvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 16 Sep 2020 21:19:26 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Gripes about walsender command processing" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> On 2020-Sep-16, Tom Lane wrote:\n>> Note that your changes need to be backpatched into v13,\n>> because AFAICS this code is violating the FE/BE protocol\n>> right now --- it's just luck that libpq isn't moaning\n>> about extra CommandComplete messages. But I don't think\n>> we want to change the ps title behavior in v13 at this\n>> late date, so that part should be HEAD-only.\n\n> I pushed to 13, but it's because of the removal of the command tag; the\n> duplicate tags we've been sending since 9.3. ¯\\_(ツ)_/¯\n\nUgh. Well, fixing v13 is an improvement anyway. Thanks!\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 16 Sep 2020 20:36:55 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Gripes about walsender command processing" } ]
[ { "msg_contents": "While implementing streaming replication client functionality for Npgsql\nI stumbled upon a minor documentation error at\nhttps://www.postgresql.org/docs/current/protocol-replication.html\n\nThe \"content\" return value for the TIMELINE_HISTORYcommand is advertised\nas bytea while it is in fact raw ASCII bytes.\n\nHow did I find out?\nSince the value I get doesn't start with a \"\\x\" and contains ascii text,\nalthough I've bytea_outputset to hex, I first thought that the streaming\nreplication protocol simply doesn't honor bytea_output, but then I\nrealized that I also get unencoded tabs and newlines which wouldn't be\npossible if the value woud be passed through byteaout.\n\nThis is certainly a minor problem since the timeline history file only\ncontains generated strings that are ASCII-only, so just using the\nunencoded bytes is actually easier than decoding bytea.\nOTOH it did cost me a few hours (writing a bytea decoder and figuring\nout why it doesn't work by looking at varlena.c and proving the docs\nwrong) so I want to point this out here since it is possibly an\nunintended behavior or at least a documentation error.\nAlso I'm wary of taking dependency on an undocumented implementation\ndetail that could possibly change at any point.\n\nRegards,\nBrar\n\n\n\n", "msg_date": "Sun, 13 Sep 2020 22:25:01 +0200", "msg_from": "Brar Piening <brar@gmx.de>", "msg_from_op": true, "msg_subject": "Minor documentation error regarding streaming replication protocol" }, { "msg_contents": "Brar Piening wrote:\n> This is certainly a minor problem\n\nAfter thinking about it a little more I think that at least the fact\nthat even the row description message advertises the content as bytea\ncould be considered as a bug - no?\n\n\n\n\n", "msg_date": "Sun, 13 Sep 2020 22:33:36 +0200", "msg_from": "Brar Piening <brar@gmx.de>", "msg_from_op": true, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "On Sun, Sep 13, 2020 at 10:25:01PM +0200, Brar Piening wrote:\n> While implementing streaming replication client functionality for Npgsql\n> I stumbled upon a minor documentation error at\n> https://www.postgresql.org/docs/current/protocol-replication.html\n> \n> The \"content\" return value for the TIMELINE_HISTORYcommand is advertised\n> as bytea while it is in fact raw ASCII bytes.\n> \n> How did I find out?\n> Since the value I get doesn't start with a \"\\x\" and contains ascii text,\n> although I've bytea_outputset to hex, I first thought that the streaming\n> replication protocol simply doesn't honor bytea_output, but then I\n> realized that I also get unencoded tabs and newlines which wouldn't be\n> possible if the value woud be passed through byteaout.\n> \n> This is certainly a minor problem since the timeline history file only\n> contains generated strings that are ASCII-only, so just using the\n> unencoded bytes is actually easier than decoding bytea.\n> OTOH it did cost me a few hours (writing a bytea decoder and figuring\n> out why it doesn't work by looking at varlena.c and proving the docs\n> wrong) so I want to point this out here since it is possibly an\n> unintended behavior or at least a documentation error.\n> Also I'm wary of taking dependency on an undocumented implementation\n> detail that could possibly change at any point.\n\nI have looked at this. It seems SendTimeLineHistory() is sending raw\nbytes from the history file, with no encoding conversion, and\nReceiveXlogStream() is receiving it, again assuming it is just plain\ntext. I am not sure we really have an SQL data type where we do this. \nBYTEA doesn't do encoding conversion, but does backslash procesing, and\nTEXT does encoding conversion.\n\nI suppose we either have to document this as BYTEA with no backslash\nprocessing, or TEXT with no encoding conversion --- I think I prefer the\nlater.\n\nAttached is a patch to update the docs, and the data type passed by\nSendTimeLineHistory(). Does this look safe to everyone?\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee", "msg_date": "Thu, 8 Oct 2020 16:23:06 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "On Thu, Oct 08, 2020 at 04:23:06PM -0400, Bruce Momjian wrote:\n> I have looked at this. It seems SendTimeLineHistory() is sending raw\n> bytes from the history file, with no encoding conversion, and\n> ReceiveXlogStream() is receiving it, again assuming it is just plain\n> text. I am not sure we really have an SQL data type where we do this. \n> BYTEA doesn't do encoding conversion, but does backslash procesing, and\n> TEXT does encoding conversion.\n> \n> I suppose we either have to document this as BYTEA with no backslash\n> processing, or TEXT with no encoding conversion --- I think I prefer the\n> later.\n\nAs StartupXLOG() tells, The timeline history file can include as\nreason the recovery target name which may not be made just of ASCII\ncharacters as that's the value specified in pg_create_restore_point by\nthe user, so bytea is correct, no?\n--\nMichael", "msg_date": "Fri, 9 Oct 2020 08:52:50 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "On Fri, Oct 9, 2020 at 08:52:50AM +0900, Michael Paquier wrote:\n> On Thu, Oct 08, 2020 at 04:23:06PM -0400, Bruce Momjian wrote:\n> > I have looked at this. It seems SendTimeLineHistory() is sending raw\n> > bytes from the history file, with no encoding conversion, and\n> > ReceiveXlogStream() is receiving it, again assuming it is just plain\n> > text. I am not sure we really have an SQL data type where we do this. \n> > BYTEA doesn't do encoding conversion, but does backslash procesing, and\n> > TEXT does encoding conversion.\n> > \n> > I suppose we either have to document this as BYTEA with no backslash\n> > processing, or TEXT with no encoding conversion --- I think I prefer the\n> > later.\n> \n> As StartupXLOG() tells, The timeline history file can include as\n> reason the recovery target name which may not be made just of ASCII\n> characters as that's the value specified in pg_create_restore_point by\n> the user, so bytea is correct, no?\n\nGood point. The reporter was assuming the data would come to the client\nin the bytea output format specified by the GUC, e.g. \\x..., so that\ndoesn't happen either. As I said before, it is more raw bytes, but we\ndon't have an SQL data type for that.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Thu, 8 Oct 2020 23:17:59 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "On Thu, Oct 8, 2020 at 11:17:59PM -0400, Bruce Momjian wrote:\n> Good point. The reporter was assuming the data would come to the client\n> in the bytea output format specified by the GUC, e.g. \\x..., so that\n> doesn't happen either. As I said before, it is more raw bytes, but we\n> don't have an SQL data type for that.\n\nI did some more research on this. It turns out timeline 'content' is\nthe only BYTEA listed in the protocol docs, even though it just passes C\nstrings to pq_sendbytes(), just like many other fields like the field\nabove it, the timeline history filename. The proper fix is to change\nthe code to return the timeline history file contents as TEXT instead of\nBYTEA.\n\nPatch attached. I would like to backpatch this to all supported\nversions so we are consistent and people don't think different PG\nversions use different return values for this. Is that safe? Looking\nat the uses of this in our code, it seems so. We aren't doing BYTEA\nescaping or TEXT encoding conversion in any of these cases.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee", "msg_date": "Wed, 14 Oct 2020 16:46:59 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "Bruce Momjian <bruce@momjian.us> writes:\n> Patch attached. I would like to backpatch this to all supported\n> versions so we are consistent and people don't think different PG\n> versions use different return values for this. Is that safe? Looking\n> at the uses of this in our code, it seems so. We aren't doing BYTEA\n> escaping or TEXT encoding conversion in any of these cases.\n\nI do not think a back-patch is a good idea. Yeah, it probably\nwon't break anything, but by the same token it won't fix anything.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 14 Oct 2020 17:10:30 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "On Wed, Oct 14, 2020 at 05:10:30PM -0400, Tom Lane wrote:\n> Bruce Momjian <bruce@momjian.us> writes:\n> > Patch attached. I would like to backpatch this to all supported\n> > versions so we are consistent and people don't think different PG\n> > versions use different return values for this. Is that safe? Looking\n> > at the uses of this in our code, it seems so. We aren't doing BYTEA\n> > escaping or TEXT encoding conversion in any of these cases.\n> \n> I do not think a back-patch is a good idea. Yeah, it probably\n> won't break anything, but by the same token it won't fix anything.\n\nOK, I can instead put in a C comment that it is really TEXT like the\nother fields, but update the docs in all branches. Does that work for\neveryone?\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Wed, 14 Oct 2020 22:25:38 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "Bruce Momjian <bruce(at)momjian(dot)us> wrote:\n>> Good point. The reporter was assuming the data would come to the client\n>> in the bytea output format specified by the GUC, e.g. \\x..., so that\n>> doesn't happen either. As I said before, it is more raw bytes, but we\n>> don't have an SQL data type for that.\n\n> I did some more research on this. It turns out timeline 'content' is\n> the only BYTEA listed in the protocol docs, even though it just passes C\n> strings to pq_sendbytes(), just like many other fields like the field\n> above it, the timeline history filename. The proper fix is to change\n> the code to return the timeline history file contents as TEXT instead of\n> BYTEA.\n\nIn the light of what Michael wrote above, I don't think that this is really enough.\n\nIf the timeline history file can contain strings which \"may not be made just of ASCII characters\" this would probably make the client side assume that the content is being sent as TEXT encoded in client_encoding which again isn't true.\nIn the worst case this could lead to nasty decoding bugs on the client side which could even result in security issues.\n\nSince you probably can't tell in which encoding the aforementioned \"recovery target name\" was written to the timeline history file, I agree with Michael that BYTEA is probably the sanest way to send this file.\n\nIMO the best way out of this is to either really encode the content as BYTEA by passing it through byteaout() and by that escaping characters <0x20 and >0x7e, or to document that the file is being sent \"as raw bytes that can be read as 'bytea Escape Format' by parsers compatible with byteain()\" (this works because byteain() doesn't check whether bytes <0x20 or >0x7e are actually escaped).\n\nAgain, reading the raw bytes, either via byteain() or just as raw bytes, isn't really a problem and I don't want to bring you into a situation where the cure is worse than the disease.\n\n\n", "msg_date": "Thu, 15 Oct 2020 08:27:51 +0200", "msg_from": "Brar Piening <Brar@gmx.de>", "msg_from_op": false, "msg_subject": "Aw: Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "Brar Piening <Brar@gmx.de> writes:\n> Bruce Momjian <bruce(at)momjian(dot)us> wrote:\n>> I did some more research on this. It turns out timeline 'content' is\n>> the only BYTEA listed in the protocol docs, even though it just passes C\n>> strings to pq_sendbytes(), just like many other fields like the field\n>> above it, the timeline history filename. The proper fix is to change\n>> the code to return the timeline history file contents as TEXT instead of\n>> BYTEA.\n\n> If the timeline history file can contain strings which \"may not be made just of ASCII characters\" this would probably make the client side assume that the content is being sent as TEXT encoded in client_encoding which again isn't true.\n\nI think this is overthinking the problem, TBH. Yeah, perhaps somebody\nput non-ASCII comments into that file, but they'd probably be expecting\nthe exact same encoding they used there to come out the other end.\n\nWe should certainly *not* apply byteaout, as that would break cases that\nwork fine today; and if we do not do that, it is quite misleading to\nsuggest that the data is given in bytea format.\n\nI don't really see why our only documentation choices are \"text\" or\n\"bytea\". Can't we just write \"(raw file contents)\" or the like?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 15 Oct 2020 10:03:46 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Aw: Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "\n\nOn 2020/10/15 23:03, Tom Lane wrote:\n> Brar Piening <Brar@gmx.de> writes:\n>> Bruce Momjian <bruce(at)momjian(dot)us> wrote:\n>>> I did some more research on this. It turns out timeline 'content' is\n>>> the only BYTEA listed in the protocol docs, even though it just passes C\n>>> strings to pq_sendbytes(), just like many other fields like the field\n>>> above it, the timeline history filename. The proper fix is to change\n>>> the code to return the timeline history file contents as TEXT instead of\n>>> BYTEA.\n> \n>> If the timeline history file can contain strings which \"may not be made just of ASCII characters\" this would probably make the client side assume that the content is being sent as TEXT encoded in client_encoding which again isn't true.\n> \n> I think this is overthinking the problem, TBH. Yeah, perhaps somebody\n> put non-ASCII comments into that file, but they'd probably be expecting\n> the exact same encoding they used there to come out the other end.\n> \n> We should certainly *not* apply byteaout, as that would break cases that\n> work fine today;\n\n+1\n\n> and if we do not do that, it is quite misleading to\n> suggest that the data is given in bytea format.\n> \n> I don't really see why our only documentation choices are \"text\" or\n> \"bytea\". Can't we just write \"(raw file contents)\" or the like?\n\n+1\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 15 Oct 2020 23:23:05 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Aw: Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "On Thu, Oct 15, 2020 at 10:03:46AM -0400, Tom Lane wrote:\n> Brar Piening <Brar@gmx.de> writes:\n> > Bruce Momjian <bruce(at)momjian(dot)us> wrote:\n> >> I did some more research on this. It turns out timeline 'content' is\n> >> the only BYTEA listed in the protocol docs, even though it just passes C\n> >> strings to pq_sendbytes(), just like many other fields like the field\n> >> above it, the timeline history filename. The proper fix is to change\n> >> the code to return the timeline history file contents as TEXT instead of\n> >> BYTEA.\n> \n> > If the timeline history file can contain strings which \"may not be made just of ASCII characters\" this would probably make the client side assume that the content is being sent as TEXT encoded in client_encoding which again isn't true.\n> \n> I think this is overthinking the problem, TBH. Yeah, perhaps somebody\n> put non-ASCII comments into that file, but they'd probably be expecting\n> the exact same encoding they used there to come out the other end.\n> \n> We should certainly *not* apply byteaout, as that would break cases that\n> work fine today; and if we do not do that, it is quite misleading to\n> suggest that the data is given in bytea format.\n> \n> I don't really see why our only documentation choices are \"text\" or\n> \"bytea\". Can't we just write \"(raw file contents)\" or the like?\n\nAgreed. The reason they are those labels is that the C code has to\nlabel the output fields, so it can only use SQL types. There are many\nprotocol fields mislabeled in this way, not just timeline history.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Thu, 15 Oct 2020 11:14:15 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Aw: Re: Minor documentation error regarding streaming\n replication protocol" }, { "msg_contents": "Bruce Momjian <bruce@momjian.us> writes:\n> On Thu, Oct 15, 2020 at 10:03:46AM -0400, Tom Lane wrote:\n>> I don't really see why our only documentation choices are \"text\" or\n>> \"bytea\". Can't we just write \"(raw file contents)\" or the like?\n\n> Agreed. The reason they are those labels is that the C code has to\n> label the output fields, so it can only use SQL types. There are many\n> protocol fields mislabeled in this way, not just timeline history.\n\nAh, right. Well, let's label it as text and then in the description\nof the message, note that the field contains the raw file contents,\nwhose encoding is unknown to the server.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 15 Oct 2020 11:18:33 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Aw: Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Well, let's label it as text and then in the description\n> of the message, note that the field contains the raw file contents,\n> whose encoding is unknown to the server.\n\n+1\n\nThis would definitely have solved my initial issue and looks like a sane way forward without over-engineering the problem or causing any backwards-compatibility issues.\n\nRegards,\nBrar Piening\n\n\n", "msg_date": "Thu, 15 Oct 2020 17:36:38 +0200", "msg_from": "Brar Piening <Brar@gmx.de>", "msg_from_op": false, "msg_subject": "Aw: Re: Re: Minor documentation error regarding streaming\n replication protocol" }, { "msg_contents": "On Thu, Oct 15, 2020 at 11:18:33AM -0400, Tom Lane wrote:\n> Bruce Momjian <bruce@momjian.us> writes:\n> > On Thu, Oct 15, 2020 at 10:03:46AM -0400, Tom Lane wrote:\n> >> I don't really see why our only documentation choices are \"text\" or\n> >> \"bytea\". Can't we just write \"(raw file contents)\" or the like?\n> \n> > Agreed. The reason they are those labels is that the C code has to\n> > label the output fields, so it can only use SQL types. There are many\n> > protocol fields mislabeled in this way, not just timeline history.\n> \n> Ah, right. Well, let's label it as text and then in the description\n> of the message, note that the field contains the raw file contents,\n> whose encoding is unknown to the server.\n\nOK, but this not would need to be in the protocol docs at the top, not\nfor the timeline history file, since it affects all columns labeled as\nTEXT.\n\nWe would want the timeline history file contents label changed from\nBYTEA to TEXT in the docs changed for all supported versions, add a C\ncomment to all backbranches that BYTEA is the same as TEXT protocol\nfields, and change the C code to return TEXT IN PG 14. Is that what\npeople want?\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Thu, 15 Oct 2020 11:45:44 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Aw: Re: Minor documentation error regarding streaming\n replication protocol" }, { "msg_contents": "Bruce Momjian <bruce@momjian.us> writes:\n> We would want the timeline history file contents label changed from\n> BYTEA to TEXT in the docs changed for all supported versions, add a C\n> comment to all backbranches that BYTEA is the same as TEXT protocol\n> fields, and change the C code to return TEXT IN PG 14. Is that what\n> people want?\n\nI still think there is no need to touch back branches. What you\npropose here is more likely to confuse people than help them.\nHaving the documentation disagree with the code about how the\nfield is labeled is not good either.\n\nFurthermore, it absolutely does not make sense to say (or imply)\nthat the unknown-encoding business applies to all text fields.\nThere are a very small number of fields where we should say that.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 15 Oct 2020 12:01:21 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Aw: Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "On Thu, Oct 15, 2020 at 12:01:21PM -0400, Tom Lane wrote:\n> Bruce Momjian <bruce@momjian.us> writes:\n> > We would want the timeline history file contents label changed from\n> > BYTEA to TEXT in the docs changed for all supported versions, add a C\n> > comment to all backbranches that BYTEA is the same as TEXT protocol\n> > fields, and change the C code to return TEXT IN PG 14. Is that what\n> > people want?\n> \n> I still think there is no need to touch back branches. What you\n> propose here is more likely to confuse people than help them.\n> Having the documentation disagree with the code about how the\n> field is labeled is not good either.\n\nUnderstood.\n\n> Furthermore, it absolutely does not make sense to say (or imply)\n> that the unknown-encoding business applies to all text fields.\n> There are a very small number of fields where we should say that.\n\nYes, I am seeing now that even IDENTIFY_SYSTEM above it properly does\nencoding. I guess TIMELINE_HISTORY works this way because it is pulling\nfrom the file system, not from system tables. I ended up with just a\nnew doc sentence and C comment in back branches, and a relabeling of the\ntimeline history 'content' field as TEXT in the C code and docs,\nattached.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee", "msg_date": "Thu, 15 Oct 2020 12:43:22 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Aw: Re: Minor documentation error regarding streaming\n replication protocol" }, { "msg_contents": "On Thu, Oct 15, 2020 at 12:43:22PM -0400, Bruce Momjian wrote:\n> On Thu, Oct 15, 2020 at 12:01:21PM -0400, Tom Lane wrote:\n> > Bruce Momjian <bruce@momjian.us> writes:\n> > > We would want the timeline history file contents label changed from\n> > > BYTEA to TEXT in the docs changed for all supported versions, add a C\n> > > comment to all backbranches that BYTEA is the same as TEXT protocol\n> > > fields, and change the C code to return TEXT IN PG 14. Is that what\n> > > people want?\n> > \n> > I still think there is no need to touch back branches. What you\n> > propose here is more likely to confuse people than help them.\n> > Having the documentation disagree with the code about how the\n> > field is labeled is not good either.\n> \n> Understood.\n> \n> > Furthermore, it absolutely does not make sense to say (or imply)\n> > that the unknown-encoding business applies to all text fields.\n> > There are a very small number of fields where we should say that.\n> \n> Yes, I am seeing now that even IDENTIFY_SYSTEM above it properly does\n> encoding. I guess TIMELINE_HISTORY works this way because it is pulling\n> from the file system, not from system tables. I ended up with just a\n> new doc sentence and C comment in back branches, and a relabeling of the\n> timeline history 'content' field as TEXT in the C code and docs,\n> attached.\n\nI have applied the doc-only patch to back branches, and the data type\nchange to master; the master change should cause no behavioral change.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Thu, 12 Nov 2020 14:36:22 -0500", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Aw: Re: Minor documentation error regarding streaming\n replication protocol" }, { "msg_contents": "On Thu, 2020-10-08 at 23:17 -0400, Bruce Momjian wrote:\n> As I said before, it is more raw bytes, but\n> we\n> don't have an SQL data type for that.\n\nSorry to jump in to this thread late.\n\nCan't we just set both \"filename\" and \"content\" to be BYTEA, but then\nset the format code to 1 (indicating binary)?\n\nFor clients that do look at the descriptor, they are more likely to get\nit right; and for clients that don't look at the descriptor, there will\nbe no change.\n\nRegards,\n\tJeff Davis\n\n\n\n\n", "msg_date": "Tue, 01 Dec 2020 10:16:31 -0800", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "On Tue, Dec 1, 2020 at 10:16:31AM -0800, Jeff Davis wrote:\n> On Thu, 2020-10-08 at 23:17 -0400, Bruce Momjian wrote:\n> > As I said before, it is more raw bytes, but\n> > we\n> > don't have an SQL data type for that.\n> \n> Sorry to jump in to this thread late.\n> \n> Can't we just set both \"filename\" and \"content\" to be BYTEA, but then\n> set the format code to 1 (indicating binary)?\n> \n> For clients that do look at the descriptor, they are more likely to get\n> it right; and for clients that don't look at the descriptor, there will\n> be no change.\n\nYes, we could, but I thought the format code was not something we set at\nthis level. Looking at byteasend() it is true it just sends the bytes.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Wed, 2 Dec 2020 15:16:30 -0500", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "On Wed, 2020-12-02 at 15:16 -0500, Bruce Momjian wrote:\n> Yes, we could, but I thought the format code was not something we set\n> at\n> this level. Looking at byteasend() it is true it just sends the\n> bytes.\n\nIt can be set along with the type. Attached an example.\n\nAndres objected (in a separate conversation) to forcing a binary-format \nvalue on a client that didn't ask for one. He suggested that we mandate\nthat the data is ASCII-only (for both filename and content), closing\nthe gap Michael raised[1]; and then just declare all values to be text\nformat.\n\nI am fine with either approach; but in any case, I don't see the point\nin sending an incorrect RowDescription.\n\nRegards,\n\tJeff Davis\n\n[1] https://postgr.es/m/20201008235250.GA1528@paquier.xyz", "msg_date": "Thu, 03 Dec 2020 09:04:21 -0800", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "On Thu, Dec 3, 2020 at 09:04:21AM -0800, Jeff Davis wrote:\n> On Wed, 2020-12-02 at 15:16 -0500, Bruce Momjian wrote:\n> > Yes, we could, but I thought the format code was not something we set\n> > at\n> > this level. Looking at byteasend() it is true it just sends the\n> > bytes.\n> \n> It can be set along with the type. Attached an example.\n> \n> Andres objected (in a separate conversation) to forcing a binary-format \n> value on a client that didn't ask for one. He suggested that we mandate\n> that the data is ASCII-only (for both filename and content), closing\n> the gap Michael raised[1]; and then just declare all values to be text\n> format.\n\nHow do we mandate that? Just mention it in the docs and C comments?\n\n> I am fine with either approach; but in any case, I don't see the point\n> in sending an incorrect RowDescription.\n\nYeah, I can see that argument, particularly since you are setting binary\nfor the entire row, which in this case is valid, but still, kind of odd.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Thu, 3 Dec 2020 13:14:56 -0500", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "On Thu, 2020-12-03 at 13:14 -0500, Bruce Momjian wrote:\n> How do we mandate that? Just mention it in the docs and C comments?\n\nCan't we just throw an error in pg_create_restore_point() if any high\nbits are set? And perhaps error or Assert at a later point in case we\nchange the code in such a way as to let non-ASCII data in there.\n\nThis is probably the best approach, and it builds on your previous\npatch (which already got consensus) rather than replacing it.\n\nRegards,\n\tJeff Davis\n\n\n\n\n", "msg_date": "Mon, 07 Dec 2020 15:24:14 -0800", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "On Thu, 2020-12-03 at 13:14 -0500, Bruce Momjian wrote:\n> Andres objected (in a separate conversation) to forcing a binary-\n> > format \n> > value on a client that didn't ask for one. He suggested that we\n> > mandate\n> > that the data is ASCII-only (for both filename and content),\n> > closing\n> > the gap Michael raised[1]; and then just declare all values to be\n> > text\n> > format.\n> \n> How do we mandate that? Just mention it in the docs and C comments?\n\nAttached a simple patch that enforces an all-ASCII restore point name\nrather than documenting the possibility of non-ASCII text.\n\nRegards,\n\tJeff Davis\n\n[1] \nhttps://www.postgresql.org/message-id/3679218.1602770626%40sss.pgh.pa.us", "msg_date": "Tue, 15 Dec 2020 01:22:44 -0800", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "Hi,\n\nOn 2020-12-15 01:22:44 -0800, Jeff Davis wrote:\n> Attached a simple patch that enforces an all-ASCII restore point name\n> rather than documenting the possibility of non-ASCII text.\n\n+1\n\n\n> diff --git a/src/backend/access/transam/xlogfuncs.c b/src/backend/access/transam/xlogfuncs.c\n> index 290658b22c..48daed56f6 100644\n> --- a/src/backend/access/transam/xlogfuncs.c\n> +++ b/src/backend/access/transam/xlogfuncs.c\n> @@ -44,6 +44,8 @@\n> static StringInfo label_file;\n> static StringInfo tblspc_map_file;\n> \n> +static bool is_all_ascii(const char *str);\n\nMinor nit: I'd put this into common/string.[ch], besides\npg_clean_ascii(). Probably renaming it to pg_is_ascii().\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 15 Dec 2020 12:54:51 -0800", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "On Tue, Dec 15, 2020 at 01:22:44AM -0800, Jeff Davis wrote:\n> On Thu, 2020-12-03 at 13:14 -0500, Bruce Momjian wrote:\n> > Andres objected (in a separate conversation) to forcing a binary-\n> > > format \n> > > value on a client that didn't ask for one. He suggested that we\n> > > mandate\n> > > that the data is ASCII-only (for both filename and content),\n> > > closing\n> > > the gap Michael raised[1]; and then just declare all values to be\n> > > text\n> > > format.\n> > \n> > How do we mandate that? Just mention it in the docs and C comments?\n> \n> Attached a simple patch that enforces an all-ASCII restore point name\n> rather than documenting the possibility of non-ASCII text.\n\nOh, nice idea, sure. Would you like to apply it? Master only or\nbackpatch?\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EnterpriseDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Tue, 15 Dec 2020 17:28:09 -0500", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "On Tue, Dec 15, 2020 at 12:54:51PM -0800, Andres Freund wrote:\n> Minor nit: I'd put this into common/string.[ch], besides\n> pg_clean_ascii(). Probably renaming it to pg_is_ascii().\n\nYeah. There is already one pg_is_ascii_string() in saslprep.c,\nis_all_ascii() in collationcmds.c and string_is_ascii() in\npgp-pgsql.c. I don't think we need a fourth copy of the same logic,\neven if it is dead simple.\n--\nMichael", "msg_date": "Wed, 16 Dec 2020 09:30:36 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "Jeff Davis wrote:\n> Attached a simple patch that enforces an all-ASCII restore point name\n> rather than documenting the possibility of non-ASCII text.\n\n+1\n\nThis is probably the best solution because it gives guarantees to the\nclient without causing compatibility issues with old clients.\n\nThanks!\n\nBrar\n\n\n\n", "msg_date": "Wed, 16 Dec 2020 11:00:44 +0100", "msg_from": "Brar Piening <brar@gmx.de>", "msg_from_op": true, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "On Tue, 2020-12-15 at 12:54 -0800, Andres Freund wrote:\n> Hi,\n> \n> On 2020-12-15 01:22:44 -0800, Jeff Davis wrote:\n> > Attached a simple patch that enforces an all-ASCII restore point\n> > name\n> > rather than documenting the possibility of non-ASCII text.\n> \n> +1\n\nOn second thought, I'm going to retract this patch. The docs[1] say:\n\n\"You can, if you like, add comments to a history file to record your\nown notes about how and why this particular timeline was created. Such\ncomments will be especially valuable when you have a thicket of\ndifferent timelines as a result of experimentation.\"\n\nIt doesn't say how the comments should be written, but they are\napparently \"#\"-style comments, and presumably can contain text in\nwhatever encoding you want, and will be sent along to the client.\n\nI don't see a lot of value in taking an already minor hole and closing\nit halfway.\n\nChanging the descriptor to be bytea-binary would be a principled\nsolution, but others objected and I don't have strong enough feelings\nabout it. I can live with the documentation note mentioning that it's\nreally binary data, and just ignore the descriptor.\n\nRegards,\n\tJeff Davis\n\n[1] \nhttps://www.postgresql.org/docs/current/continuous-archiving.html#BACKUP-TIMELINES\n\n\n\n\n", "msg_date": "Thu, 17 Dec 2020 15:13:25 -0800", "msg_from": "Jeff Davis <pgsql@j-davis.com>", "msg_from_op": false, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "On Thu, Dec 17, 2020 at 03:13:25PM -0800, Jeff Davis wrote:\n> On second thought, I'm going to retract this patch. The docs[1] say:\n> \n> \"You can, if you like, add comments to a history file to record your\n> own notes about how and why this particular timeline was created. Such\n> comments will be especially valuable when you have a thicket of\n> different timelines as a result of experimentation.\"\n\nThis actually rings a bell. Now that I think about it, I have seen in\nthe past Japanese customers making use of Japanese characters in\nhistory files. I am adding Fujii-san and Horiguchi-san in CC for more\ndetails as I recall that they were involved in such things, with\npg_rman coming first into mind. (No idea about French users.)\n--\nMichael", "msg_date": "Fri, 18 Dec 2020 10:18:45 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" }, { "msg_contents": "At Fri, 18 Dec 2020 10:18:45 +0900, Michael Paquier <michael@paquier.xyz> wrote in \n> On Thu, Dec 17, 2020 at 03:13:25PM -0800, Jeff Davis wrote:\n> > On second thought, I'm going to retract this patch. The docs[1] say:\n> > \n> > \"You can, if you like, add comments to a history file to record your\n> > own notes about how and why this particular timeline was created. Such\n> > comments will be especially valuable when you have a thicket of\n> > different timelines as a result of experimentation.\"\n> \n> This actually rings a bell. Now that I think about it, I have seen in\n> the past Japanese customers making use of Japanese characters in\n> history files. I am adding Fujii-san and Horiguchi-san in CC for more\n> details as I recall that they were involved in such things, with\n> pg_rman coming first into mind. (No idea about French users.)\n\nSorry, my faint memory says that something like that happened on\nbackup label but I don't recall that clearly.\n\npg_basebackup can set the LABEL field in the file and the string fed\nto the command's \"-l\" option is copied to there as-is (that is,\ngetting no conversion), as far as client encoding is valid as server\nencoding. (since database encoding of walsender is always SQL_ASCII)\nI'm not sure it is the expected behavior.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 18 Dec 2020 17:30:56 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Minor documentation error regarding streaming replication\n protocol" } ]
[ { "msg_contents": "Hi,\n\nAttached fixes $subject.\n\nThanks,\nNaoki Nakamichi", "msg_date": "Mon, 14 Sep 2020 11:06:15 +0900", "msg_from": "btnakamichin <btnakamichin@oss.nttdata.com>", "msg_from_op": true, "msg_subject": "typo in snapmgr.c and procarray.c" }, { "msg_contents": "\n\nOn 2020/09/14 11:06, btnakamichin wrote:\n> Hi,\n> \n> Attached fixes $subject.\n\nThanks for the patch! LGTM. I will commit it.\n\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Mon, 14 Sep 2020 11:14:44 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: typo in snapmgr.c and procarray.c" }, { "msg_contents": "\n\nOn 2020/09/14 11:14, Fujii Masao wrote:\n> \n> \n> On 2020/09/14 11:06, btnakamichin wrote:\n>> Hi,\n>>\n>> Attached fixes $subject.\n> \n> Thanks for the patch! LGTM. I will commit it.\n\nPushed. Thanks!\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Mon, 14 Sep 2020 14:17:34 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: typo in snapmgr.c and procarray.c" } ]
[ { "msg_contents": "pg_verifybackup and the associated backup manifest functionality uses \n\"path\", \"path name\", etc. throughout where other components might just \nsay \"file\", \"file name\". This isn't wrong, if you follow POSIX \nterminology, but it's a bit unusual, I think. Specifically, option \nnaming like\n\n -i, --ignore=RELATIVE_PATH ignore indicated path\n -m, --manifest-path=PATH use specified path for manifest\n -w, --wal-directory=PATH use specified path for WAL files\n\nmight make one think that there is a search path involved.\n\nThoughts? Is there a deeper reason behind this, or should we dial this \nback a bit perhaps?\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 14 Sep 2020 10:57:23 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "unusual use of \"path\" in pg_verifybackup?" } ]
[ { "msg_contents": "Hi all.\r\n\r\nI tried searching for the response to this but couldn’t find any. Tried also posting to general but got no love there.\r\n\r\nI have pg_restore running in parallel (3 or more) and processing large amount of data that is in partitioned tables. However it seems that sometime deadlock appears when one process is trying to process primary key on parent table while data still hasn’t been loaded into partitions. And acquires Exclusive Lock on the whole table. Then another process comes and tries to load one of the partitions with SharedLock but it fails.\r\n\r\nThis of course doesn’t happen always; depending on the course of actions of the pg_restore. But often enough to cause frustration.\r\n\r\nProcess 15858 waits for AccessShareLock on relation 233358134 of database 233346697; blocked by process 15861.\r\nProcess 15861 waits for AccessExclusiveLock on relation 233374757 of database 233346697; blocked by process 15858.\r\nProcess 15858: TRUNCATE TABLE ONLY myschema.\"myTable:2020-09-01\";\r\nProcess 15861: ALTER TABLE ONLY myschema.\"myTable\" ADD CONSTRAINT \"pk_myTable\" PRIMARY KEY (\"ID\", date);\r\n\r\nShould this be treated as a bug or am I doing something wrong?\r\n\r\nDisclamer: --load-via-partition-root was NOT used. Meaning that warning from the pg_dump documentation should not be applicable 😊\r\n\r\nThanx,\r\nDomagoj\r\n\r\n\n\n\n\n\n\n\n\n\nHi all.\nI tried searching for the response to this but couldn’t find any. Tried also posting to general but got no love there.\r\n\nI have pg_restore running in parallel (3 or more) and processing large amount of data that is in partitioned tables. However it seems that sometime deadlock appears when one process is trying to process primary key on parent table while data still hasn’t\r\n been loaded into partitions. And acquires Exclusive Lock on the whole table. Then another process comes and tries to load one of the partitions with SharedLock but it fails.\nThis of course doesn’t happen always; depending on the course of actions of the pg_restore. But often enough to cause frustration.\nProcess 15858 waits for AccessShareLock on relation 233358134 of database 233346697; blocked by process 15861.\r\nProcess 15861 waits for AccessExclusiveLock on relation 233374757 of database 233346697; blocked by process 15858.\r\nProcess 15858: TRUNCATE TABLE ONLY myschema.\"myTable:2020-09-01\";\r\nProcess 15861: ALTER TABLE ONLY myschema.\"myTable\" ADD CONSTRAINT \"pk_myTable\" PRIMARY KEY (\"ID\", date);\nShould this be treated as a bug or am I doing something wrong?\nDisclamer: --load-via-partition-root was NOT used. Meaning that warning from the pg_dump documentation should not be applicable\r\n😊\nThanx,\r\nDomagoj", "msg_date": "Mon, 14 Sep 2020 12:27:13 +0000", "msg_from": "Domagoj Smoljanovic <domagoj.smoljanovic@oradian.com>", "msg_from_op": true, "msg_subject": "pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "Domagoj Smoljanovic <domagoj.smoljanovic@oradian.com> writes:\n> I have pg_restore running in parallel (3 or more) and processing large amount of data that is in partitioned tables. However it seems that sometime deadlock appears when one process is trying to process primary key on parent table while data still hasn’t been loaded into partitions. And acquires Exclusive Lock on the whole table. Then another process comes and tries to load one of the partitions with SharedLock but it fails.\n\n> This of course doesn’t happen always; depending on the course of actions of the pg_restore. But often enough to cause frustration.\n\n> Process 15858 waits for AccessShareLock on relation 233358134 of database 233346697; blocked by process 15861.\n> Process 15861 waits for AccessExclusiveLock on relation 233374757 of database 233346697; blocked by process 15858.\n> Process 15858: TRUNCATE TABLE ONLY myschema.\"myTable:2020-09-01\";\n> Process 15861: ALTER TABLE ONLY myschema.\"myTable\" ADD CONSTRAINT \"pk_myTable\" PRIMARY KEY (\"ID\", date);\n\nHm, this seems related to 2ba5b2db7, but not the same thing.\nAlvaro, any thoughts?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 14 Sep 2020 10:17:28 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "On 2020-Sep-14, Tom Lane wrote:\n\n> Domagoj Smoljanovic <domagoj.smoljanovic@oradian.com> writes:\n> > I have pg_restore running in parallel (3 or more) and processing large amount of data that is in partitioned tables. However it seems that sometime deadlock appears when one process is trying to process primary key on parent table while data still hasn’t been loaded into partitions. And acquires Exclusive Lock on the whole table. Then another process comes and tries to load one of the partitions with SharedLock but it fails.\n> \n> > This of course doesn’t happen always; depending on the course of actions of the pg_restore. But often enough to cause frustration.\n> \n> > Process 15858 waits for AccessShareLock on relation 233358134 of database 233346697; blocked by process 15861.\n> > Process 15861 waits for AccessExclusiveLock on relation 233374757 of database 233346697; blocked by process 15858.\n> > Process 15858: TRUNCATE TABLE ONLY myschema.\"myTable:2020-09-01\";\n> > Process 15861: ALTER TABLE ONLY myschema.\"myTable\" ADD CONSTRAINT \"pk_myTable\" PRIMARY KEY (\"ID\", date);\n> \n> Hm, this seems related to 2ba5b2db7, but not the same thing.\n> Alvaro, any thoughts?\n\nSo apparently when we go to restore the table data for the partition,\nthe TRUNCATE deadlocks with the PK addition ... that's pretty odd;\nshouldn't the constraint restore have waited until the data had been\nfully loaded?\n\n-- \nÁlvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 14 Sep 2020 11:40:04 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "Forgot to mention the versions:\r\npg_restore (PostgreSQL) 12.4\r\nsource/ destination databases also 12.4\r\n\r\nD.\r\n\r\n-----Original Message-----\r\nFrom: Alvaro Herrera <alvherre@2ndquadrant.com> \r\nSent: 14. rujna 2020. 16:40\r\nTo: Tom Lane <tgl@sss.pgh.pa.us>\r\nCc: Domagoj Smoljanovic <domagoj.smoljanovic@oradian.com>; pgsql-hackers@postgresql.org\r\nSubject: Re: pg_restore causing deadlocks on partitioned tables\r\n\r\nOn 2020-Sep-14, Tom Lane wrote:\r\n\r\n> Domagoj Smoljanovic <domagoj.smoljanovic@oradian.com> writes:\r\n> > I have pg_restore running in parallel (3 or more) and processing large amount of data that is in partitioned tables. However it seems that sometime deadlock appears when one process is trying to process primary key on parent table while data still hasn’t been loaded into partitions. And acquires Exclusive Lock on the whole table. Then another process comes and tries to load one of the partitions with SharedLock but it fails.\r\n> \r\n> > This of course doesn’t happen always; depending on the course of actions of the pg_restore. But often enough to cause frustration.\r\n> \r\n> > Process 15858 waits for AccessShareLock on relation 233358134 of database 233346697; blocked by process 15861.\r\n> > Process 15861 waits for AccessExclusiveLock on relation 233374757 of database 233346697; blocked by process 15858.\r\n> > Process 15858: TRUNCATE TABLE ONLY myschema.\"myTable:2020-09-01\"; \r\n> > Process 15861: ALTER TABLE ONLY myschema.\"myTable\" ADD CONSTRAINT \r\n> > \"pk_myTable\" PRIMARY KEY (\"ID\", date);\r\n> \r\n> Hm, this seems related to 2ba5b2db7, but not the same thing.\r\n> Alvaro, any thoughts?\r\n\r\nSo apparently when we go to restore the table data for the partition, the TRUNCATE deadlocks with the PK addition ... that's pretty odd; shouldn't the constraint restore have waited until the data had been fully loaded?\r\n\r\n-- \r\nÁlvaro Herrera https://eur01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fwww.2ndquadrant.com%2F&amp;data=01%7C01%7Cdomagoj.smoljanovic%40oradian.com%7Cf9054c64e75a49adac3308d858bc1423%7Cc3d7e30ad09240c8b35c54a27682c60d%7C0&amp;sdata=9pphCt1EzkEzrCuCg8CLdRywknjNiG6WLfRhR4T7qPQ%3D&amp;reserved=0\r\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\r\n", "msg_date": "Mon, 14 Sep 2020 14:49:45 +0000", "msg_from": "Domagoj Smoljanovic <domagoj.smoljanovic@oradian.com>", "msg_from_op": true, "msg_subject": "RE: pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> On 2020-Sep-14, Tom Lane wrote:\n>> Hm, this seems related to 2ba5b2db7, but not the same thing.\n>> Alvaro, any thoughts?\n\n> So apparently when we go to restore the table data for the partition,\n> the TRUNCATE deadlocks with the PK addition ... that's pretty odd;\n> shouldn't the constraint restore have waited until the data had been\n> fully loaded?\n\nYeah, that's certainly the design expectation. Missing dependency?\n\nIf memory serves, which it may not given my undercaffeinated state,\nwe would not expect there to be a direct dependency link between the\nconstraint and the table data \"object\". What there should be is\ndependencies forcing the data to be restored before the post-data\nboundary pseudo-object, and the constraint after the boundary.\nI'm half guessing that that's being mucked up for partitioned tables.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 14 Sep 2020 11:24:51 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "I wrote:\n> If memory serves, which it may not given my undercaffeinated state,\n> we would not expect there to be a direct dependency link between the\n> constraint and the table data \"object\". What there should be is\n> dependencies forcing the data to be restored before the post-data\n> boundary pseudo-object, and the constraint after the boundary.\n\nNo, that's wrong: the boundary objects only exist inside pg_dump.\n\nLooking more closely, we have a deadlock between data restore\nfor a partition:\n\nProcess 15858: TRUNCATE TABLE ONLY myschema.\"myTable:2020-09-01\";\n\nand adding a PK to what I assume is its parent partitioned table:\n\nProcess 15861: ALTER TABLE ONLY myschema.\"myTable\" ADD CONSTRAINT \"pk_myTable\" PRIMARY KEY (\"ID\", date);\n\nSince that's an ALTER TABLE ONLY, it shouldn't be trying to touch the\nchild partitions at all; while the TRUNCATE should only be trying to touch\nthe child partition. At least, that's what pg_dump is expecting.\n\nHowever, the deadlock report suggests, and manual experimentation\nconfirms, that\n\n(1) TRUNCATE on a partition tries to get AccessShareLock on the parent;\n\n(2) ALTER TABLE ONLY ... ADD CONSTRAINT on a partition root tries to get\nAccessExclusiveLock on all child partitions, despite the ONLY.\n\nEach of these facts violates pg_dump's expectations about what can be\ndone in parallel with what. There's no obvious reason why we need such\nconcurrency-killing locks for these operations, either. So I think\nwhat we have here are two distinct backend bugs, not a pg_dump bug.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 14 Sep 2020 15:26:04 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "I wrote:\n> However, the deadlock report suggests, and manual experimentation\n> confirms, that\n\n> (1) TRUNCATE on a partition tries to get AccessShareLock on the parent;\n\nThe reason for this is that\n\n(a) ExecuteTruncateGuts calls InitResultRelInfo, because it might\nneed that to fire TRUNCATE triggers for the child relation.\n\n(b) InitResultRelInfo calls RelationGetPartitionQual, which\nof course(?) must access the parent table.\n\nAFAICS, it is utterly silly for InitResultRelInfo to be forcing\na partition qual to be computed when we might not need it.\nWe could flush ResultRelInfo.ri_PartitionCheck altogether and\nhave anything that was reading it instead do\nRelationGetPartitionQual(ResultRelInfo.ri_RelationDesc).\n\nActually it looks like most of the places reading it are\njust interested in non-nullness; can't those be nuked from\norbit in favor of testing rel->rd_rel->relispartition?\nThere's no such thing as a partition with an empty partition\nqual is there? (Or even if it's possible, do we care about\noptimizing the case?)\n\n> (2) ALTER TABLE ONLY ... ADD CONSTRAINT on a partition root tries to get\n> AccessExclusiveLock on all child partitions, despite the ONLY.\n\nThe cause of this seems to be that ATPrepSetNotNull is too dumb to\navoid recursing to all the child tables when the parent is already\nattnotnull. Or is there a reason we have to recurse anyway?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 14 Sep 2020 18:28:09 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "On 2020-Sep-14, Tom Lane wrote:\n\n> > (1) TRUNCATE on a partition tries to get AccessShareLock on the parent;\n> \n> The reason for this is that\n> \n> (a) ExecuteTruncateGuts calls InitResultRelInfo, because it might\n> need that to fire TRUNCATE triggers for the child relation.\n\nHmm, this seems legitimate, but of course we don't need the partition\nqual. So the reported bug would be solved with just the change to avoid\nloading ri_PartitionExpr until needed.\n\n> AFAICS, it is utterly silly for InitResultRelInfo to be forcing\n> a partition qual to be computed when we might not need it.\n> We could flush ResultRelInfo.ri_PartitionCheck altogether and\n> have anything that was reading it instead do\n> RelationGetPartitionQual(ResultRelInfo.ri_RelationDesc).\n\nHmm, but I presume we don't want to compute it every time. I suggest we\nwould still have it, but we'd only computed it when first used.\n\n> Actually it looks like most of the places reading it are\n> just interested in non-nullness; can't those be nuked from\n> orbit in favor of testing rel->rd_rel->relispartition?\n> There's no such thing as a partition with an empty partition\n> qual is there? (Or even if it's possible, do we care about\n> optimizing the case?)\n\nActually, there is one such case -- when the default partition is the\nonly partition, its constraint is empty. This has caused at least one\nbug. Maybe it'd be better if we used something like constant true\ninstead ... since we're not likely to care much about the performance of\nthat case. But I don't think that would change this patch any.\n\n> > (2) ALTER TABLE ONLY ... ADD CONSTRAINT on a partition root tries to get\n> > AccessExclusiveLock on all child partitions, despite the ONLY.\n> \n> The cause of this seems to be that ATPrepSetNotNull is too dumb to\n> avoid recursing to all the child tables when the parent is already\n> attnotnull. Or is there a reason we have to recurse anyway?\n\nHmm, looking at ATExecSetNotNull, we invoke the PostAlter hook even when\nthere's no change, so if we supressed the recursion early, that would\nchange. But I doubt we actually care.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 14 Sep 2020 20:07:21 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "I wrote:\n>> (2) ALTER TABLE ONLY ... ADD CONSTRAINT on a partition root tries to get\n>> AccessExclusiveLock on all child partitions, despite the ONLY.\n\n> The cause of this seems to be that ATPrepSetNotNull is too dumb to\n> avoid recursing to all the child tables when the parent is already\n> attnotnull. Or is there a reason we have to recurse anyway?\n\nI wrote a quick patch for this part. It seems pretty safe and probably\ncould be back-patched without fear. (I also noticed that\nATSimpleRecursion is being unnecessarily stupid: instead of the\ndemonstrably not-future-proof relkind check, it could test relhassubclass,\nwhich is not only simpler and less likely to need future changes, but\nis able to save a scan of pg_inherits in a lot more cases.)\n\nAs far as I can tell in some quick testing, this fix is sufficient to\nresolve the complained-of deadlock. It'd still be a good idea to fix the\nTRUNCATE side of things as well. But that would be hard to back-patch\nbecause removing ri_PartitionCheck, or even just failing to fill it,\nseems like a potential ABI break for extensions. So my proposal is\nto back-patch this, but address the ResultRelInfo change only in HEAD.\n\n\t\t\tregards, tom lane", "msg_date": "Mon, 14 Sep 2020 20:08:58 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> On 2020-Sep-14, Tom Lane wrote:\n>> AFAICS, it is utterly silly for InitResultRelInfo to be forcing\n>> a partition qual to be computed when we might not need it.\n>> We could flush ResultRelInfo.ri_PartitionCheck altogether and\n>> have anything that was reading it instead do\n>> RelationGetPartitionQual(ResultRelInfo.ri_RelationDesc).\n\n> Hmm, but I presume we don't want to compute it every time. I suggest we\n> would still have it, but we'd only computed it when first used.\n\nRelationGetPartitionQual already does that caching.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 15 Sep 2020 00:47:26 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "On Tue, Sep 15, 2020 at 9:09 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> I wrote:\n> >> (2) ALTER TABLE ONLY ... ADD CONSTRAINT on a partition root tries to get\n> >> AccessExclusiveLock on all child partitions, despite the ONLY.\n>\n> > The cause of this seems to be that ATPrepSetNotNull is too dumb to\n> > avoid recursing to all the child tables when the parent is already\n> > attnotnull. Or is there a reason we have to recurse anyway?\n>\n> I wrote a quick patch for this part. It seems pretty safe and probably\n> could be back-patched without fear.\n\nThe patch changes existing behavior in one case as shown below:\n\ndrop table if exists foo cascade;\ncreate table foo (a int not null);\ncreate table child () inherits (foo);\nalter table child alter a drop not null;\nalter table foo alter a set not null;\ninsert into child select null;\n\nCurrently, the last statement gives a \"not null violated\" error, but\nno longer with the patch, because the alter statement before that now\nfinishes without setting NOT NULL in child.\n\nThe patch's theory that if the parent column has NOT NULL set then it\nmust be set in child tables too does not actually hold for plain\ninheritance cases, because as shown above, NOT NULL can be dropped in\nchildren independently of the parent. With partitioning, dropping NOT\nNULL from child partitions is prevented:\n\ndrop table if exists bar cascade;\ncreate table bar (a int) partition by list (a);\ncreate table bar1 partition of bar (a not null) for values in (1);\nalter table bar1 alter a drop not null;\nERROR: column \"a\" is marked NOT NULL in parent table\n\n> (I also noticed that\n> ATSimpleRecursion is being unnecessarily stupid: instead of the\n> demonstrably not-future-proof relkind check, it could test relhassubclass,\n> which is not only simpler and less likely to need future changes, but\n> is able to save a scan of pg_inherits in a lot more cases.)\n\n+1\n\n--\nAmit Langote\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 15 Sep 2020 16:39:43 +0900", "msg_from": "Amit Langote <amitlangote09@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "On Tue, Sep 15, 2020 at 7:28 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> I wrote:\n> > However, the deadlock report suggests, and manual experimentation\n> > confirms, that\n>\n> > (1) TRUNCATE on a partition tries to get AccessShareLock on the parent;\n>\n> The reason for this is that\n>\n> (a) ExecuteTruncateGuts calls InitResultRelInfo, because it might\n> need that to fire TRUNCATE triggers for the child relation.\n>\n> (b) InitResultRelInfo calls RelationGetPartitionQual, which\n> of course(?) must access the parent table.\n>\n> AFAICS, it is utterly silly for InitResultRelInfo to be forcing\n> a partition qual to be computed when we might not need it.\n> We could flush ResultRelInfo.ri_PartitionCheck altogether and\n> have anything that was reading it instead do\n> RelationGetPartitionQual(ResultRelInfo.ri_RelationDesc).\n>\n> Actually it looks like most of the places reading it are\n> just interested in non-nullness; can't those be nuked from\n> orbit in favor of testing rel->rd_rel->relispartition?\n\nYeah, makes sense. Please see attached a patch to do that.\n\n-- \nAmit Langote\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Tue, 15 Sep 2020 20:21:43 +0900", "msg_from": "Amit Langote <amitlangote09@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "Amit Langote <amitlangote09@gmail.com> writes:\n> On Tue, Sep 15, 2020 at 9:09 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> I wrote a quick patch for this part. It seems pretty safe and probably\n>> could be back-patched without fear.\n\n> The patch's theory that if the parent column has NOT NULL set then it\n> must be set in child tables too does not actually hold for plain\n> inheritance cases, because as shown above, NOT NULL can be dropped in\n> children independently of the parent.\n\nAh, right. That seems like a bug but we have not attempted to fix it.\nBut we could restrict the optimization to partitioned tables, where\nthe assumption does hold, no?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 15 Sep 2020 09:47:31 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "On Tue, Sep 15, 2020 at 10:47 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Amit Langote <amitlangote09@gmail.com> writes:\n> > On Tue, Sep 15, 2020 at 9:09 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >> I wrote a quick patch for this part. It seems pretty safe and probably\n> >> could be back-patched without fear.\n>\n> > The patch's theory that if the parent column has NOT NULL set then it\n> > must be set in child tables too does not actually hold for plain\n> > inheritance cases, because as shown above, NOT NULL can be dropped in\n> > children independently of the parent.\n>\n> Ah, right. That seems like a bug but we have not attempted to fix it.\n\nIIRC, when this behavior was brought up as a bug in past discussions,\nit was decided that it will be fixed when NOT NULL constraints are\nrepresented using pg_constraint entries.\n\n> But we could restrict the optimization to partitioned tables, where\n> the assumption does hold, no?\n\nYeah, seems safe in their case.\n\n-- \nAmit Langote\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 15 Sep 2020 23:07:30 +0900", "msg_from": "Amit Langote <amitlangote09@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "Amit Langote <amitlangote09@gmail.com> writes:\n> On Tue, Sep 15, 2020 at 10:47 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> Ah, right. That seems like a bug but we have not attempted to fix it.\n\n> IIRC, when this behavior was brought up as a bug in past discussions,\n> it was decided that it will be fixed when NOT NULL constraints are\n> represented using pg_constraint entries.\n\nYeah, that matches my recollection too.\n\n>> But we could restrict the optimization to partitioned tables, where\n>> the assumption does hold, no?\n\n> Yeah, seems safe in their case.\n\nAnd that's sufficient to cover pg_restore's issue, since it's\nonly going to be trying to do this for partitioned tables.\n\nI'll wait till tomorrow to push this, since we're still in\nfreeze mode for the v13 branch.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 15 Sep 2020 10:15:12 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "Amit Langote <amitlangote09@gmail.com> writes:\n> On Tue, Sep 15, 2020 at 7:28 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> AFAICS, it is utterly silly for InitResultRelInfo to be forcing\n>> a partition qual to be computed when we might not need it.\n>> We could flush ResultRelInfo.ri_PartitionCheck altogether and\n>> have anything that was reading it instead do\n>> RelationGetPartitionQual(ResultRelInfo.ri_RelationDesc).\n\n> Yeah, makes sense. Please see attached a patch to do that.\n\nJust eyeballing this, this bit seems bogus:\n\n@@ -1904,7 +1903,7 @@ ExecConstraints(ResultRelInfo *resultRelInfo,\n \tBitmapset *insertedCols;\n \tBitmapset *updatedCols;\n \n-\tAssert(constr || resultRelInfo->ri_PartitionCheck);\n+\tAssert(constr);\n \n \tif (constr && constr->has_not_null)\n \t{\n\nIt does look like all the call sites check for the rel having constraints\nbefore calling, so the modified Assert may not be failing ... but why\nare we asserting and then also making a run-time test?\n\nMy inclination is to just drop the Assert as useless. There's no\nparticular reason for this function to make it a hard requirement\nthat callers optimize away unnecessary calls.\n\nI'm suspicious of the business in ExecPartitionCheck about constructing\na constant-true expression. I think executing that is likely to add\nmore cycles than you save by not running through this code each time;\nonce relcache has cached the knowledge that the partition expression\nis empty, all the steps here are pretty darn cheap ... which no doubt\nis why there wasn't a comparable optimization already. If you're\nreally concerned about that it'd be better to add a separate\n\"bool ri_PartitionCheckExprValid\" flag. (Perhaps that's worth doing\nto avoid impacts from relcache flushes; though I remain unconvinced\nthat optimizing for the empty-expression case is useful.)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 15 Sep 2020 13:41:02 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "On Wed, Sep 16, 2020 at 2:41 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Amit Langote <amitlangote09@gmail.com> writes:\n> > On Tue, Sep 15, 2020 at 7:28 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >> AFAICS, it is utterly silly for InitResultRelInfo to be forcing\n> >> a partition qual to be computed when we might not need it.\n> >> We could flush ResultRelInfo.ri_PartitionCheck altogether and\n> >> have anything that was reading it instead do\n> >> RelationGetPartitionQual(ResultRelInfo.ri_RelationDesc).\n>\n> > Yeah, makes sense. Please see attached a patch to do that.\n>\n> Just eyeballing this, this bit seems bogus:\n>\n> @@ -1904,7 +1903,7 @@ ExecConstraints(ResultRelInfo *resultRelInfo,\n> Bitmapset *insertedCols;\n> Bitmapset *updatedCols;\n>\n> - Assert(constr || resultRelInfo->ri_PartitionCheck);\n> + Assert(constr);\n>\n> if (constr && constr->has_not_null)\n> {\n>\n> It does look like all the call sites check for the rel having constraints\n> before calling, so the modified Assert may not be failing ... but why\n> are we asserting and then also making a run-time test?\n>\n> My inclination is to just drop the Assert as useless. There's no\n> particular reason for this function to make it a hard requirement\n> that callers optimize away unnecessary calls.\n\nYeah, the Assert seems pretty pointless at this point.\n\n> I'm suspicious of the business in ExecPartitionCheck about constructing\n> a constant-true expression. I think executing that is likely to add\n> more cycles than you save by not running through this code each time;\n> once relcache has cached the knowledge that the partition expression\n> is empty, all the steps here are pretty darn cheap ... which no doubt\n> is why there wasn't a comparable optimization already.\n\nAh, you're right.\n\n> If you're\n> really concerned about that it'd be better to add a separate\n> \"bool ri_PartitionCheckExprValid\" flag. (Perhaps that's worth doing\n> to avoid impacts from relcache flushes; though I remain unconvinced\n> that optimizing for the empty-expression case is useful.)\n\nAgreed that it's not really necessary to optimize that case.\n\nUpdated patch attached.\n\n-- \nAmit Langote\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Wed, 16 Sep 2020 11:10:17 +0900", "msg_from": "Amit Langote <amitlangote09@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "Amit Langote <amitlangote09@gmail.com> writes:\n> Updated patch attached.\n\nPushed with a little bit of fooling about. After looking at the\ngit history, I saw that the Assert we were wondering about used to\nbe just \"Assert(constr)\", and there were not run-time checks on\nwhether constr is null. That was changed when f0e44751d added\npartition constraint checking into ExecConstraints' responsibilities.\nAt some later point that code was removed from ExecConstraints,\nbut we failed to undo the other changes in ExecConstraints, leaving\nit looking pretty silly. So I reverted this to the way it was,\nwith just an Assert and no regular checks.\n\nI also did a bit more work on the comments. (Speaking of which,\nis there a better place to put the commentary you removed from\nInitResultRelInfo? It was surely wildly out of place there,\nbut I'm wondering if maybe we have a README that should cover it.)\n\nI pushed this to HEAD only, and the other patch as far back as\nv12, so we will have a solution to the deadlock problem in v12.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 16 Sep 2020 14:40:41 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "Thanx Tom and Amit for the effort. \n\nLooking forward to try it out.\nD.\n\n-----Original Message-----\nFrom: Tom Lane <tgl@sss.pgh.pa.us> \nSent: 16. rujna 2020. 20:41\nTo: Amit Langote <amitlangote09@gmail.com>\nCc: Alvaro Herrera <alvherre@2ndquadrant.com>; Domagoj Smoljanovic <domagoj.smoljanovic@oradian.com>; pgsql-hackers@postgresql.org\nSubject: Re: pg_restore causing deadlocks on partitioned tables\n\nAmit Langote <amitlangote09@gmail.com> writes:\n> Updated patch attached.\n\nPushed with a little bit of fooling about. After looking at the git history, I saw that the Assert we were wondering about used to be just \"Assert(constr)\", and there were not run-time checks on whether constr is null. That was changed when f0e44751d added partition constraint checking into ExecConstraints' responsibilities.\nAt some later point that code was removed from ExecConstraints, but we failed to undo the other changes in ExecConstraints, leaving it looking pretty silly. So I reverted this to the way it was, with just an Assert and no regular checks.\n\nI also did a bit more work on the comments. (Speaking of which, is there a better place to put the commentary you removed from InitResultRelInfo? It was surely wildly out of place there, but I'm wondering if maybe we have a README that should cover it.)\n\nI pushed this to HEAD only, and the other patch as far back as v12, so we will have a solution to the deadlock problem in v12.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 16 Sep 2020 21:56:46 +0000", "msg_from": "Domagoj Smoljanovic <domagoj.smoljanovic@oradian.com>", "msg_from_op": true, "msg_subject": "RE: pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "On Thu, Sep 17, 2020 at 3:40 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Amit Langote <amitlangote09@gmail.com> writes:\n> > Updated patch attached.\n>\n> Pushed with a little bit of fooling about.\n\nThank you.\n\n> After looking at the\n> git history, I saw that the Assert we were wondering about used to\n> be just \"Assert(constr)\", and there were not run-time checks on\n> whether constr is null. That was changed when f0e44751d added\n> partition constraint checking into ExecConstraints' responsibilities.\n> At some later point that code was removed from ExecConstraints,\n> but we failed to undo the other changes in ExecConstraints, leaving\n> it looking pretty silly. So I reverted this to the way it was,\n> with just an Assert and no regular checks.\n>\n> I also did a bit more work on the comments. (Speaking of which,\n> is there a better place to put the commentary you removed from\n> InitResultRelInfo? It was surely wildly out of place there,\n> but I'm wondering if maybe we have a README that should cover it.)\n\nActually, the two points of interest in that now removed comment,\nwhich was this:\n\n- * Partition constraint, which also includes the partition constraint of\n- * all the ancestors that are partitions. Note that it will be checked\n- * even in the case of tuple-routing where this table is the target leaf\n- * partition, if there any BR triggers defined on the table. Although\n- * tuple-routing implicitly preserves the partition constraint of the\n- * target partition for a given row, the BR triggers may change the row\n- * such that the constraint is no longer satisfied, which we must fail for\n- * by checking it explicitly.\n- *\n- * If this is a partitioned table, the partition constraint (if any) of a\n- * given row will be checked just before performing tuple-routing.\n\nare also mentioned, although in less words, where they are relevant:\n\nIn ExecInsert():\n\n /*\n * Also check the tuple against the partition constraint, if there is\n * one; except that if we got here via tuple-routing, we don't need to\n * if there's no BR trigger defined on the partition.\n */\n if (resultRelationDesc->rd_rel->relispartition &&\n (resultRelInfo->ri_PartitionRoot == NULL ||\n (resultRelInfo->ri_TrigDesc &&\n resultRelInfo->ri_TrigDesc->trig_insert_before_row)))\n ExecPartitionCheck(resultRelInfo, slot, estate, true);\n\nIn ExecFindPartition():\n\n /*\n * First check the root table's partition constraint, if any. No point in\n * routing the tuple if it doesn't belong in the root table itself.\n */\n if (rootResultRelInfo->ri_RelationDesc->rd_rel->relispartition)\n ExecPartitionCheck(rootResultRelInfo, slot, estate, true);\n\nMaybe that's enough?\n\n-- \nAmit Langote\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 17 Sep 2020 11:01:32 +0900", "msg_from": "Amit Langote <amitlangote09@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pg_restore causing deadlocks on partitioned tables" }, { "msg_contents": "Amit Langote <amitlangote09@gmail.com> writes:\n> On Thu, Sep 17, 2020 at 3:40 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> I also did a bit more work on the comments. (Speaking of which,\n>> is there a better place to put the commentary you removed from\n>> InitResultRelInfo? It was surely wildly out of place there,\n>> but I'm wondering if maybe we have a README that should cover it.)\n\n> Actually, the two points of interest in that now removed comment,\n> which was this:\n> ...\n> are also mentioned, although in less words, where they are relevant:\n\nAh, good.\n\n> Maybe that's enough?\n\nWorks for me. Thanks for checking that.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 16 Sep 2020 22:03:57 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pg_restore causing deadlocks on partitioned tables" } ]
[ { "msg_contents": "Hi,\n\n1. wchar2char has a mistake when checking the return of WideCharToMultiByte\ncall.\nresult variable is unsigned, therefore, cannot be less than zero, returning\n-1 is not an option.\n\n2. strftime or strftime_win32, return cannot be less than zero.\n\n3. If strftime or strftime_win32, fails, why not abort the loop?\n\nregards,\nRanier Vilela", "msg_date": "Mon, 14 Sep 2020 09:41:36 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Fix overflow at return wchar2char (src/backend/utils/adt/pg_locale.c)" }, { "msg_contents": "> On 14 Sep 2020, at 14:41, Ranier Vilela <ranier.vf@gmail.com> wrote:\n\n> 1. wchar2char has a mistake when checking the return of WideCharToMultiByte call.\n> result variable is unsigned, therefore, cannot be less than zero, returning -1 is not an option.\n\nIf the objection is that an unsigned var is tested with <= 0, then changing the\nsemantics of the function seems a rather drastic solution:\n\n \t\t/* A zero return is failure */\n-\t\tif (result <= 0)\n-\t\t\tresult = -1;\n+\t\tif (result == 0)\n+\t\t\treturn 0;\n\nThe comment for wchar2char explicitly state \"This has the same API as the\nstandard wcstombs_l() function;\", and man wcstombs_l shows:\n\n RETURN VALUES\n\t The wcstombs() function returns the number of bytes converted (not\n\t including any terminating null), if successful; otherwise, it returns\n\t (size_t)-1.\n\nIt can of course be argued that the check should be \"result == 0\" as result is\nof type size_t. The original commit introducing this in 2007, 654dcfb9e4b6,\nhad an integer return variable, so it's just a carry-over from there. Will\nchanging that buy us anything, except possibly silence a static analyzer?\n\n> 2. strftime or strftime_win32, return cannot be less than zero.\n> \n> 3. If strftime or strftime_win32, fails, why not abort the loop?\n\nThis recently changed in 7ad1cd31bfc, and the commit message along with the\ncomment above the code implies that an error is unlikely:,\n\n * MAX_L10N_DATA is sufficient buffer space for every known locale, and\n * POSIX defines no strftime() errors. (Buffer space exhaustion is not an\n * error.)\n\n..so it's probably a case of not optimizing for never-happens-scenarios: The\nfact that strftimefail will trigger elog and not ereport is an additional clue\nthat an error is unlikely.\n\ncheers ./daniel\n\n", "msg_date": "Mon, 14 Sep 2020 15:53:01 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Fix overflow at return wchar2char\n (src/backend/utils/adt/pg_locale.c)" }, { "msg_contents": "Em seg., 14 de set. de 2020 às 10:53, Daniel Gustafsson <daniel@yesql.se>\nescreveu:\n\n> > On 14 Sep 2020, at 14:41, Ranier Vilela <ranier.vf@gmail.com> wrote:\n>\n> > 1. wchar2char has a mistake when checking the return of\n> WideCharToMultiByte call.\n> > result variable is unsigned, therefore, cannot be less than zero,\n> returning -1 is not an option.\n>\n> If the objection is that an unsigned var is tested with <= 0, then\n> changing the\n> semantics of the function seems a rather drastic solution:\n>\n> /* A zero return is failure */\n> - if (result <= 0)\n> - result = -1;\n> + if (result == 0)\n> + return 0;\n>\n> The comment for wchar2char explicitly state \"This has the same API as the\n> standard wcstombs_l() function;\", and man wcstombs_l shows:\n>\n> RETURN VALUES\n> The wcstombs() function returns the number of bytes converted (not\n> including any terminating null), if successful; otherwise, it\n> returns\n> (size_t)-1.\n>\nI'm not agree that must, follow wcstombs_l API.\nAnd there is already a precedent in returning zero.\n\nBut if wchar2char must be follow wcstombs_l API.\nwchar2char all calls must be:\n\nresult = wchar2char();\nif (result == 0 || result == (size_t)-1) {\n\nSee at lowerstr_with_len (src/backend/tsearch/ts_locale.c):\n\nwlen = char2wchar(wstr, len + 1, str, len, mylocale); // fail with -1\nAssert((void) 0); // Release mode, Assert(wlen <= len);\nwlen = 18446744073709551615;\nlen = pg_database_encoding_max_length() * 18446744073709551615 + 1; //\nlen is int, Windows LLP64 is 32 bits.\nout = (char *) palloc(len);\n\n\n> > 2. strftime or strftime_win32, return cannot be less than zero.\n> >\n> > 3. If strftime or strftime_win32, fails, why not abort the loop?\n>\n> This recently changed in 7ad1cd31bfc, and the commit message along with the\n> comment above the code implies that an error is unlikely:,\n>\n> * MAX_L10N_DATA is sufficient buffer space for every known locale, and\n> * POSIX defines no strftime() errors. (Buffer space exhaustion is not\n> an\n> * error.)\n>\n> ..so it's probably a case of not optimizing for never-happens-scenarios:\n> The\n> fact that strftimefail will trigger elog and not ereport is an additional\n> clue\n> that an error is unlikely.\n>\nThe cost of the test, It has been paid, then the break is free.\nAnd testing unsigned if it is less than zero, it is useless,\nit just gets in the way of the compiler.\n\nregards,\nRanier Vilela\n\nEm seg., 14 de set. de 2020 às 10:53, Daniel Gustafsson <daniel@yesql.se> escreveu:> On 14 Sep 2020, at 14:41, Ranier Vilela <ranier.vf@gmail.com> wrote:\n\n> 1. wchar2char has a mistake when checking the return of WideCharToMultiByte call.\n> result variable is unsigned, therefore, cannot be less than zero, returning -1 is not an option.\n\nIf the objection is that an unsigned var is tested with <= 0, then changing the\nsemantics of the function seems a rather drastic solution:\n\n                /* A zero return is failure */\n-               if (result <= 0)\n-                       result = -1;\n+               if (result == 0)\n+                       return 0;\n\nThe comment for wchar2char explicitly state \"This has the same API as the\nstandard wcstombs_l() function;\", and man wcstombs_l shows:\n\n    RETURN VALUES\n         The wcstombs() function returns the number of bytes converted (not\n         including any terminating null), if successful; otherwise, it returns\n         (size_t)-1.I'm not agree that must, follow wcstombs_l API.And there is already a precedent in returning zero.But if \nwchar2char must be follow \nwcstombs_l API. \nwchar2char all calls must be:result = wchar2char();\n\nif (result == 0 || result == (size_t)-1) {See at \nlowerstr_with_len \n\n(src/backend/tsearch/ts_locale.c):\t\twlen = char2wchar(wstr, len + 1, str, len, mylocale);  // fail with -1Assert((void) 0);  // Release mode, Assert(wlen <= len);wlen = \n18446744073709551615;len = pg_database_encoding_max_length() * \n18446744073709551615\n\n + 1;  // len is int, Windows LLP64 is 32 bits.\t\tout = (char *) palloc(len);\n\n> 2. strftime or strftime_win32, return cannot be less than zero.\n> \n> 3. If strftime or strftime_win32, fails, why not abort the loop?\n\nThis recently changed in 7ad1cd31bfc, and the commit message along with the\ncomment above the code implies that an error is unlikely:,\n\n    * MAX_L10N_DATA is sufficient buffer space for every known locale, and\n    * POSIX defines no strftime() errors.  (Buffer space exhaustion is not an\n    * error.)\n\n..so it's probably a case of not optimizing for never-happens-scenarios: The\nfact that strftimefail will trigger elog and not ereport is an additional clue\nthat an error is unlikely.The cost of the test, It has been paid, then the break is free.And testing unsigned if it is less than zero, it is useless, it just gets in the way of the compiler.regards,Ranier Vilela", "msg_date": "Mon, 14 Sep 2020 12:59:38 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Fix overflow at return wchar2char\n (src/backend/utils/adt/pg_locale.c)" }, { "msg_contents": "Ranier Vilela <ranier.vf@gmail.com> writes:\n> Em seg., 14 de set. de 2020 às 10:53, Daniel Gustafsson <daniel@yesql.se>\n> escreveu:\n>> If the objection is that an unsigned var is tested with <= 0, then\n>> changing the\n>> semantics of the function seems a rather drastic solution:\n\n> But if wchar2char must be follow wcstombs_l API.\n> wchar2char all calls must be:\n\n> result = wchar2char();\n> if (result == 0 || result == (size_t)-1) {\n\n> See at lowerstr_with_len (src/backend/tsearch/ts_locale.c):\n\nActually, lowerstr_with_len is perfectly fine. It's coercing the\nsize_t result to int, so (size_t) -1 becomes integer -1 and its\nerror check for wlen < 0 is correct. It might have a problem if\nthe coercion to int could overflow, but that cannot happen because\nof our restrictions on the size of a palloc'd chunk.\n\nThere are some other call sites that are failing to check at all,\nwhich is not so good. But changing the function's API to be both\nnonstandard and ambiguous (because a zero result is a perfectly valid\ncase) doesn't help fix that.\n\nI concur with Daniel that none of the changes shown here are\nworthwhile improvements. It's not illegal to test an unsigned\nvariable for \"x <= 0\".\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 14 Sep 2020 14:07:58 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Fix overflow at return wchar2char\n (src/backend/utils/adt/pg_locale.c)" } ]
[ { "msg_contents": "In connection with a nearby thread, I tried to run the subscription\ntest suite in a CLOBBER_CACHE_ALWAYS build. I soon found that I had\nto increase wal_receiver_timeout, but after doing this:\n\ndiff --git a/src/test/perl/PostgresNode.pm b/src/test/perl/PostgresNode.pm\nindex 1488bff..5fe6810 100644\n*** a/src/test/perl/PostgresNode.pm\n--- b/src/test/perl/PostgresNode.pm\n*************** sub init\n*** 447,452 ****\n--- 447,453 ----\n print $conf \"log_statement = all\\n\";\n print $conf \"log_replication_commands = on\\n\";\n print $conf \"wal_retrieve_retry_interval = '500ms'\\n\";\n+ print $conf \"wal_receiver_timeout = '10min'\\n\";\n \n # If a setting tends to affect whether tests pass or fail, print it after\n # TEMP_CONFIG. Otherwise, print it before TEMP_CONFIG, thereby permitting\n\nI let it run overnight, and came back to find that it was stuck at\n\n[03:02:15] t/013_partition.pl ................. 19/51\n\nand had been for circa eight hours, where extrapolation from other tests\nsaid it shouldn't take much over half an hour. Investigation found that\nthe subscriber was repeatedly failing like this:\n\n2020-09-14 11:05:26.483 EDT [1030506] LOG: logical replication apply worker for subscription \"sub1\" has started\n2020-09-14 11:05:27.139 EDT [1030506] ERROR: cache lookup failed for relation 0\n2020-09-14 11:05:27.140 EDT [947156] LOG: background worker \"logical replication worker\" (PID 1030506) exited with exit code 1\n2020-09-14 11:05:27.571 EDT [1030509] LOG: logical replication apply worker for subscription \"sub1\" has started\n2020-09-14 11:05:28.227 EDT [1030509] ERROR: cache lookup failed for relation 0\n2020-09-14 11:05:28.228 EDT [947156] LOG: background worker \"logical replication worker\" (PID 1030509) exited with exit code 1\n\nThe publisher's log shows no sign of distress:\n\n2020-09-14 11:06:09.380 EDT [1030619] sub1 LOG: statement: SELECT pg_catalog.set_config('search_path', '', false);\n2020-09-14 11:06:09.446 EDT [1030619] sub1 LOG: received replication command: IDENTIFY_SYSTEM\n2020-09-14 11:06:09.446 EDT [1030619] sub1 LOG: received replication command: START_REPLICATION SLOT \"sub1\" LOGICAL 0/163CF08 (proto_version '2', publication_names '\"pub1\"')\n2020-09-14 11:06:09.447 EDT [1030619] sub1 LOG: starting logical decoding for slot \"sub1\"\n2020-09-14 11:06:09.447 EDT [1030619] sub1 DETAIL: Streaming transactions committing after 0/163D848, reading WAL from 0/163CF08.\n2020-09-14 11:06:09.447 EDT [1030619] sub1 LOG: logical decoding found consistent point at 0/163CF08\n2020-09-14 11:06:09.447 EDT [1030619] sub1 DETAIL: There are no running transactions.\n2020-09-14 11:06:10.468 EDT [1030621] sub1 LOG: statement: SELECT pg_catalog.set_config('search_path', '', false);\n2020-09-14 11:06:10.533 EDT [1030621] sub1 LOG: received replication command: IDENTIFY_SYSTEM\n2020-09-14 11:06:10.534 EDT [1030621] sub1 LOG: received replication command: START_REPLICATION SLOT \"sub1\" LOGICAL 0/163CF08 (proto_version '2', publication_names '\"pub1\"')\n2020-09-14 11:06:10.534 EDT [1030621] sub1 LOG: starting logical decoding for slot \"sub1\"\n2020-09-14 11:06:10.534 EDT [1030621] sub1 DETAIL: Streaming transactions committing after 0/163D848, reading WAL from 0/163CF08.\n2020-09-14 11:06:10.534 EDT [1030621] sub1 LOG: logical decoding found consistent point at 0/163CF08\n2020-09-14 11:06:10.534 EDT [1030621] sub1 DETAIL: There are no running transactions.\n\nI do not have time today to chase this further, but somebody should.\n\nMore generally, this seems like good evidence that we really oughta have a\nbuildfarm member that's running *all* the tests under CLOBBER_CACHE_ALWAYS\nnot just the core tests. That seems impossibly expensive, but I realized\nwhile watching these tests that a ridiculous fraction of the runtime is\nbeing spent in repeated initdb calls. On my machine, initdb takes about\n12 minutes under CCA, so doing it separately for publisher and subscriber\nmeans 24 minutes, which compares not at all favorably to the\ncirca-half-an-hour total runtime of each of the subscription test scripts.\nWe're surely not learning anything after the first CCA run of initdb, so\nif we could find a way to skip that overhead for later runs, it'd make a\nhuge difference in the practicality of running these tests under CCA.\n\nI recall having worked on a patch to make the regression tests run\ninitdb just once, creating a template directory tree, and then \"cp -a\"\nthat into place for each test. I did not finish it, because it wasn't\nshowing a lot of advantage in a normal test run, but maybe the idea\ncould be resurrected for CCA and other slow builds.\n\nAnother idea is to make CCA a little more dynamic, say allow it to be\nsuppressed through an environment variable setting, and then use that\nto speed up per-test initdbs.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 14 Sep 2020 11:20:03 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Subscription test 013_partition.pl fails under CLOBBER_CACHE_ALWAYS" }, { "msg_contents": "Hi Tom,\n\nI have tested the subscription test 013_partition.pl with CCA enabled on\nHEAD and PG13,\nand I am able to reproduce the issue on both the versions.\n\n*Logs:*\n[centos@clobber-cache subscription]$ git branch\n* REL_13_STABLE\n master\n[centos@clobber-cache-db93 subscription]$ tail -f\ntmp_check/log/013_partition_subscriber1.log\n2020-09-15 08:42:19.763 UTC [27866] LOG: logical replication apply worker\nfor subscription \"sub1\" has started\n2020-09-15 08:42:20.395 UTC [27866] ERROR: cache lookup failed for\nrelation 0\n2020-09-15 08:42:20.436 UTC [26427] LOG: background worker \"logical\nreplication worker\" (PID 27866) exited with exit code 1\n2020-09-15 08:42:20.835 UTC [27868] LOG: logical replication apply worker\nfor subscription \"sub1\" has started\n2020-09-15 08:42:21.462 UTC [27868] ERROR: cache lookup failed for\nrelation 0\n2020-09-15 08:42:21.508 UTC [26427] LOG: background worker \"logical\nreplication worker\" (PID 27868) exited with exit code 1\n2020-09-15 08:42:21.921 UTC [27870] LOG: logical replication apply worker\nfor subscription \"sub1\" has started\n2020-09-15 08:42:22.551 UTC [27870] ERROR: cache lookup failed for\nrelation 0\n\n\nThanks.\n--\nRegards,\nNeha Sharma\n\n\nOn Mon, Sep 14, 2020 at 8:50 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> In connection with a nearby thread, I tried to run the subscription\n> test suite in a CLOBBER_CACHE_ALWAYS build. I soon found that I had\n> to increase wal_receiver_timeout, but after doing this:\n>\n> diff --git a/src/test/perl/PostgresNode.pm b/src/test/perl/PostgresNode.pm\n> index 1488bff..5fe6810 100644\n> *** a/src/test/perl/PostgresNode.pm\n> --- b/src/test/perl/PostgresNode.pm\n> *************** sub init\n> *** 447,452 ****\n> --- 447,453 ----\n> print $conf \"log_statement = all\\n\";\n> print $conf \"log_replication_commands = on\\n\";\n> print $conf \"wal_retrieve_retry_interval = '500ms'\\n\";\n> + print $conf \"wal_receiver_timeout = '10min'\\n\";\n>\n> # If a setting tends to affect whether tests pass or fail, print it\n> after\n> # TEMP_CONFIG. Otherwise, print it before TEMP_CONFIG, thereby\n> permitting\n>\n> I let it run overnight, and came back to find that it was stuck at\n>\n> [03:02:15] t/013_partition.pl ................. 19/51\n>\n> and had been for circa eight hours, where extrapolation from other tests\n> said it shouldn't take much over half an hour. Investigation found that\n> the subscriber was repeatedly failing like this:\n>\n> 2020-09-14 11:05:26.483 EDT [1030506] LOG: logical replication apply\n> worker for subscription \"sub1\" has started\n> 2020-09-14 11:05:27.139 EDT [1030506] ERROR: cache lookup failed for\n> relation 0\n> 2020-09-14 11:05:27.140 EDT [947156] LOG: background worker \"logical\n> replication worker\" (PID 1030506) exited with exit code 1\n> 2020-09-14 11:05:27.571 EDT [1030509] LOG: logical replication apply\n> worker for subscription \"sub1\" has started\n> 2020-09-14 11:05:28.227 EDT [1030509] ERROR: cache lookup failed for\n> relation 0\n> 2020-09-14 11:05:28.228 EDT [947156] LOG: background worker \"logical\n> replication worker\" (PID 1030509) exited with exit code 1\n>\n> The publisher's log shows no sign of distress:\n>\n> 2020-09-14 11:06:09.380 EDT [1030619] sub1 LOG: statement: SELECT\n> pg_catalog.set_config('search_path', '', false);\n> 2020-09-14 11:06:09.446 EDT [1030619] sub1 LOG: received replication\n> command: IDENTIFY_SYSTEM\n> 2020-09-14 11:06:09.446 EDT [1030619] sub1 LOG: received replication\n> command: START_REPLICATION SLOT \"sub1\" LOGICAL 0/163CF08 (proto_version\n> '2', publication_names '\"pub1\"')\n> 2020-09-14 11:06:09.447 EDT [1030619] sub1 LOG: starting logical decoding\n> for slot \"sub1\"\n> 2020-09-14 11:06:09.447 EDT [1030619] sub1 DETAIL: Streaming transactions\n> committing after 0/163D848, reading WAL from 0/163CF08.\n> 2020-09-14 11:06:09.447 EDT [1030619] sub1 LOG: logical decoding found\n> consistent point at 0/163CF08\n> 2020-09-14 11:06:09.447 EDT [1030619] sub1 DETAIL: There are no running\n> transactions.\n> 2020-09-14 11:06:10.468 EDT [1030621] sub1 LOG: statement: SELECT\n> pg_catalog.set_config('search_path', '', false);\n> 2020-09-14 11:06:10.533 EDT [1030621] sub1 LOG: received replication\n> command: IDENTIFY_SYSTEM\n> 2020-09-14 11:06:10.534 EDT [1030621] sub1 LOG: received replication\n> command: START_REPLICATION SLOT \"sub1\" LOGICAL 0/163CF08 (proto_version\n> '2', publication_names '\"pub1\"')\n> 2020-09-14 11:06:10.534 EDT [1030621] sub1 LOG: starting logical decoding\n> for slot \"sub1\"\n> 2020-09-14 11:06:10.534 EDT [1030621] sub1 DETAIL: Streaming transactions\n> committing after 0/163D848, reading WAL from 0/163CF08.\n> 2020-09-14 11:06:10.534 EDT [1030621] sub1 LOG: logical decoding found\n> consistent point at 0/163CF08\n> 2020-09-14 11:06:10.534 EDT [1030621] sub1 DETAIL: There are no running\n> transactions.\n>\n> I do not have time today to chase this further, but somebody should.\n>\n> More generally, this seems like good evidence that we really oughta have a\n> buildfarm member that's running *all* the tests under CLOBBER_CACHE_ALWAYS\n> not just the core tests. That seems impossibly expensive, but I realized\n> while watching these tests that a ridiculous fraction of the runtime is\n> being spent in repeated initdb calls. On my machine, initdb takes about\n> 12 minutes under CCA, so doing it separately for publisher and subscriber\n> means 24 minutes, which compares not at all favorably to the\n> circa-half-an-hour total runtime of each of the subscription test scripts.\n> We're surely not learning anything after the first CCA run of initdb, so\n> if we could find a way to skip that overhead for later runs, it'd make a\n> huge difference in the practicality of running these tests under CCA.\n>\n> I recall having worked on a patch to make the regression tests run\n> initdb just once, creating a template directory tree, and then \"cp -a\"\n> that into place for each test. I did not finish it, because it wasn't\n> showing a lot of advantage in a normal test run, but maybe the idea\n> could be resurrected for CCA and other slow builds.\n>\n> Another idea is to make CCA a little more dynamic, say allow it to be\n> suppressed through an environment variable setting, and then use that\n> to speed up per-test initdbs.\n>\n> regards, tom lane\n>\n>\n>\n\nHi Tom,I have tested the subscription test 013_partition.pl with CCA enabled on HEAD and PG13, and I am able to reproduce the issue on both the versions.Logs:[centos@clobber-cache subscription]$ git branch* REL_13_STABLE  master[centos@clobber-cache-db93 subscription]$ tail -f tmp_check/log/013_partition_subscriber1.log2020-09-15 08:42:19.763 UTC [27866] LOG:  logical replication apply worker for subscription \"sub1\" has started2020-09-15 08:42:20.395 UTC [27866] ERROR:  cache lookup failed for relation 02020-09-15 08:42:20.436 UTC [26427] LOG:  background worker \"logical replication worker\" (PID 27866) exited with exit code 12020-09-15 08:42:20.835 UTC [27868] LOG:  logical replication apply worker for subscription \"sub1\" has started2020-09-15 08:42:21.462 UTC [27868] ERROR:  cache lookup failed for relation 02020-09-15 08:42:21.508 UTC [26427] LOG:  background worker \"logical replication worker\" (PID 27868) exited with exit code 12020-09-15 08:42:21.921 UTC [27870] LOG:  logical replication apply worker for subscription \"sub1\" has started2020-09-15 08:42:22.551 UTC [27870] ERROR:  cache lookup failed for relation 0Thanks.--Regards,Neha SharmaOn Mon, Sep 14, 2020 at 8:50 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:In connection with a nearby thread, I tried to run the subscription\ntest suite in a CLOBBER_CACHE_ALWAYS build.  I soon found that I had\nto increase wal_receiver_timeout, but after doing this:\n\ndiff --git a/src/test/perl/PostgresNode.pm b/src/test/perl/PostgresNode.pm\nindex 1488bff..5fe6810 100644\n*** a/src/test/perl/PostgresNode.pm\n--- b/src/test/perl/PostgresNode.pm\n*************** sub init\n*** 447,452 ****\n--- 447,453 ----\n    print $conf \"log_statement = all\\n\";\n    print $conf \"log_replication_commands = on\\n\";\n    print $conf \"wal_retrieve_retry_interval = '500ms'\\n\";\n+   print $conf \"wal_receiver_timeout = '10min'\\n\";\n\n    # If a setting tends to affect whether tests pass or fail, print it after\n    # TEMP_CONFIG.  Otherwise, print it before TEMP_CONFIG, thereby permitting\n\nI let it run overnight, and came back to find that it was stuck at\n\n[03:02:15] t/013_partition.pl ................. 19/51\n\nand had been for circa eight hours, where extrapolation from other tests\nsaid it shouldn't take much over half an hour.  Investigation found that\nthe subscriber was repeatedly failing like this:\n\n2020-09-14 11:05:26.483 EDT [1030506] LOG:  logical replication apply worker for subscription \"sub1\" has started\n2020-09-14 11:05:27.139 EDT [1030506] ERROR:  cache lookup failed for relation 0\n2020-09-14 11:05:27.140 EDT [947156] LOG:  background worker \"logical replication worker\" (PID 1030506) exited with exit code 1\n2020-09-14 11:05:27.571 EDT [1030509] LOG:  logical replication apply worker for subscription \"sub1\" has started\n2020-09-14 11:05:28.227 EDT [1030509] ERROR:  cache lookup failed for relation 0\n2020-09-14 11:05:28.228 EDT [947156] LOG:  background worker \"logical replication worker\" (PID 1030509) exited with exit code 1\n\nThe publisher's log shows no sign of distress:\n\n2020-09-14 11:06:09.380 EDT [1030619] sub1 LOG:  statement: SELECT pg_catalog.set_config('search_path', '', false);\n2020-09-14 11:06:09.446 EDT [1030619] sub1 LOG:  received replication command: IDENTIFY_SYSTEM\n2020-09-14 11:06:09.446 EDT [1030619] sub1 LOG:  received replication command: START_REPLICATION SLOT \"sub1\" LOGICAL 0/163CF08 (proto_version '2', publication_names '\"pub1\"')\n2020-09-14 11:06:09.447 EDT [1030619] sub1 LOG:  starting logical decoding for slot \"sub1\"\n2020-09-14 11:06:09.447 EDT [1030619] sub1 DETAIL:  Streaming transactions committing after 0/163D848, reading WAL from 0/163CF08.\n2020-09-14 11:06:09.447 EDT [1030619] sub1 LOG:  logical decoding found consistent point at 0/163CF08\n2020-09-14 11:06:09.447 EDT [1030619] sub1 DETAIL:  There are no running transactions.\n2020-09-14 11:06:10.468 EDT [1030621] sub1 LOG:  statement: SELECT pg_catalog.set_config('search_path', '', false);\n2020-09-14 11:06:10.533 EDT [1030621] sub1 LOG:  received replication command: IDENTIFY_SYSTEM\n2020-09-14 11:06:10.534 EDT [1030621] sub1 LOG:  received replication command: START_REPLICATION SLOT \"sub1\" LOGICAL 0/163CF08 (proto_version '2', publication_names '\"pub1\"')\n2020-09-14 11:06:10.534 EDT [1030621] sub1 LOG:  starting logical decoding for slot \"sub1\"\n2020-09-14 11:06:10.534 EDT [1030621] sub1 DETAIL:  Streaming transactions committing after 0/163D848, reading WAL from 0/163CF08.\n2020-09-14 11:06:10.534 EDT [1030621] sub1 LOG:  logical decoding found consistent point at 0/163CF08\n2020-09-14 11:06:10.534 EDT [1030621] sub1 DETAIL:  There are no running transactions.\n\nI do not have time today to chase this further, but somebody should.\n\nMore generally, this seems like good evidence that we really oughta have a\nbuildfarm member that's running *all* the tests under CLOBBER_CACHE_ALWAYS\nnot just the core tests.  That seems impossibly expensive, but I realized\nwhile watching these tests that a ridiculous fraction of the runtime is\nbeing spent in repeated initdb calls.  On my machine, initdb takes about\n12 minutes under CCA, so doing it separately for publisher and subscriber\nmeans 24 minutes, which compares not at all favorably to the\ncirca-half-an-hour total runtime of each of the subscription test scripts.\nWe're surely not learning anything after the first CCA run of initdb, so\nif we could find a way to skip that overhead for later runs, it'd make a\nhuge difference in the practicality of running these tests under CCA.\n\nI recall having worked on a patch to make the regression tests run\ninitdb just once, creating a template directory tree, and then \"cp -a\"\nthat into place for each test.  I did not finish it, because it wasn't\nshowing a lot of advantage in a normal test run, but maybe the idea\ncould be resurrected for CCA and other slow builds.\n\nAnother idea is to make CCA a little more dynamic, say allow it to be\nsuppressed through an environment variable setting, and then use that\nto speed up per-test initdbs.\n\n                        regards, tom lane", "msg_date": "Tue, 15 Sep 2020 01:45:52 +0530", "msg_from": "Neha Sharma <neha.sharma@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Subscription test 013_partition.pl fails under\n CLOBBER_CACHE_ALWAYS" }, { "msg_contents": "I wrote:\n> [ $subject ]\n\nI found some time to trace this down, and what it turns out to be is\nthat apply_handle_truncate() is making use of a LogicalRepRelMapEntry's\nlocalreloid field without any consideration for the possibility that\nthat's been set to zero as a result of a cache flush. The visible\nsymptom of \"cache lookup failed for relation 0\" comes from trying\nto invoke find_all_inheritors with a zero OID.\n\nNow, study of apply_handle_truncate doesn't immediately reveal where\na cache flush could have occurred, but I realized that it's actually\npossible that the LogicalRepRelMapEntry is *already* marked invalid\nwhen logicalrep_rel_open() returns! That's because for some reason\nit does GetSubscriptionRelState last, after it's already marked the\nentry valid, and that function does plenty o' catalog accesses.\n\nIt's not really clear to me why setting localreloid to zero is a sane\nway to represent \"this entry needs to be revalidated\". I think a\nseparate flag would be more appropriate. Once we have lock on the\ntarget relation, it seems to me that no interesting changes should\nbe possible as long as we have lock; so there's no very good reason\nto destroy useful state to remind ourselves that we should recheck\nit next time.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 15 Sep 2020 15:46:18 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Subscription test 013_partition.pl fails under\n CLOBBER_CACHE_ALWAYS" }, { "msg_contents": "I wrote:\n> It's not really clear to me why setting localreloid to zero is a sane\n> way to represent \"this entry needs to be revalidated\". I think a\n> separate flag would be more appropriate. Once we have lock on the\n> target relation, it seems to me that no interesting changes should\n> be possible as long as we have lock; so there's no very good reason\n> to destroy useful state to remind ourselves that we should recheck\n> it next time.\n\nHere's a patch that changes that, and also cleans up some sloppy\nthinking about how to re-acquire lock on the replication target\nrelation. (Just because the OID was valid last you heard does\nnot mean that table_open is guaranteed to succeed.)\n\nWith this, we get through 013_partition.pl under CCA. I plan to\ntry to run all of subscription/ and recovery/ before concluding\nthere's nothing else to fix, though.\n\n\t\t\tregards, tom lane", "msg_date": "Tue, 15 Sep 2020 17:30:15 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Subscription test 013_partition.pl fails under\n CLOBBER_CACHE_ALWAYS" }, { "msg_contents": "I wrote:\n> With this, we get through 013_partition.pl under CCA. I plan to\n> try to run all of subscription/ and recovery/ before concluding\n> there's nothing else to fix, though.\n\nLooks like the rest passes. FTR, it was possible to get through\nsubscription/ in about 2 hours on my workstation, and recovery/ in about\n30 minutes, after hacking things so that initdb used a non-CCA backend.\nSo that's definitely a promising thing to look at if anyone wants\nto try to do this on a regular basis.\n\nAside from increasing wal_receiver_timeout as previously mentioned,\nI found I had to set a higher pg_ctl start timeout using PGCTLTIMEOUT\nin order to get through the recovery tests.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 15 Sep 2020 20:16:26 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Subscription test 013_partition.pl fails under\n CLOBBER_CACHE_ALWAYS" }, { "msg_contents": "On Wed, Sep 16, 2020 at 1:16 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> I wrote:\n> It's not really clear to me why setting localreloid to zero is a sane\n> way to represent \"this entry needs to be revalidated\". I think a\n> separate flag would be more appropriate. Once we have lock on the\n> target relation, it seems to me that no interesting changes should\n> be possible as long as we have lock; so there's no very good reason\n> to destroy useful state to remind ourselves that we should recheck\n> it next time.\n>\n\nSo, can we assume that the current code can only cause the problem in\nCCA builds bot not in any practical scenario because after having a\nlock on relation probably there shouldn't be any invalidation which\nleads to this problem?\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Wed, 16 Sep 2020 09:19:36 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Subscription test 013_partition.pl fails under\n CLOBBER_CACHE_ALWAYS" }, { "msg_contents": "Amit Kapila <amit.kapila16@gmail.com> writes:\n> So, can we assume that the current code can only cause the problem in\n> CCA builds bot not in any practical scenario because after having a\n> lock on relation probably there shouldn't be any invalidation which\n> leads to this problem?\n\nNo. The reason we expend so much time and effort on CCA testing is\nthat cache flushes are unpredictable, and they can happen even when\nyou have a lock on the object(s) in question. In particular, the\neasiest real-world case that could cause the described problem is an\nsinval queue overrun that we detect during the GetSubscriptionRelState\ncall at the bottom of logicalrep_rel_open. In that case we'll\ncome back to the caller with the LogicalRepRelMapEntry marked as\nalready needing revalidation, because the cache inval callback\nwill have marked *all* of them that way. That's actually a harmless\ncondition, because we have lock on the rel so nothing really\nchanged ... but if we blew away localreloid and the caller needs\nto use that, kaboom.\n\nWe could imagine marking the entry valid at the very bottom of\nlogicalrep_rel_open, but that just moves the problem somewhere else.\nAny caller that does *any* catalog access while holding open a\nLogicalRepRelMapEntry would not be able to rely on its localreloid\nstaying valid. That's a recipe for irreproducible bugs, and it's\nunnecessary. In practice the entry is good as long as\nwe continue to hold a lock on the local relation. So we should\nmark LogicalRepRelMapEntries as potentially-needing-revalidation\nin a way that doesn't interfere with active users of the entry.\n\nIn short: the value of CCA testing is to model sinval overruns\nhappening at any point where they could happen. The real-world\nodds of one happening at any given instant are low, but they're\nnever zero.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 16 Sep 2020 00:11:02 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Subscription test 013_partition.pl fails under\n CLOBBER_CACHE_ALWAYS" }, { "msg_contents": "On Wed, Sep 16, 2020 at 9:41 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Amit Kapila <amit.kapila16@gmail.com> writes:\n> > So, can we assume that the current code can only cause the problem in\n> > CCA builds bot not in any practical scenario because after having a\n> > lock on relation probably there shouldn't be any invalidation which\n> > leads to this problem?\n>\n>\n> In short: the value of CCA testing is to model sinval overruns\n> happening at any point where they could happen. The real-world\n> odds of one happening at any given instant are low, but they're\n> never zero.\n>\n\nThanks for the explanation. I have read your patch and it looks good to me.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Wed, 16 Sep 2020 11:23:16 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Subscription test 013_partition.pl fails under\n CLOBBER_CACHE_ALWAYS" }, { "msg_contents": "Amit Kapila <amit.kapila16@gmail.com> writes:\n> Thanks for the explanation. I have read your patch and it looks good to me.\n\nPushed, thanks for checking the patch.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 16 Sep 2020 12:09:24 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Subscription test 013_partition.pl fails under\n CLOBBER_CACHE_ALWAYS" } ]
[ { "msg_contents": "Peter Eisentraut <peter(dot)eisentraut(at)2ndquadrant(dot)com> writes:\n> ok done\nmsvc 2019 (64 bits), is worried about it:\nhttps://github.com/postgres/postgres/commit/0aa8f764088ea0f36620ae2955fa6c54ec736c46\n\n\"C:\\dll\\postgres\\pgsql.sln\" (default target) (1) ->\n\"C:\\dll\\postgres\\cyrillic_and_mic.vcxproj\" (default target) (37) ->\n\"C:\\dll\\postgres\\postgres.vcxproj\" (default target) (38) ->\n(ClCompile target) ->\n C:\\dll\\postgres\\src\\backend\\utils\\adt\\dbsize.c(630,20): warning C4334:\n'<<': resultado de 32-bit shift convertido implicitamente para 64 bits\n(64-bit shift era pretendid\no?) [C:\\dll\\postgres\\postgres.vcxproj]\n\n 1 Warning(s)\n 0 Error(s)\n\n\"result of 32-bit shift implicitly converted to 64 bits (was 64-bit shift\nintended?)\"\n\nregards,\nRanier Vilela\n\n\nPeter Eisentraut <peter(dot)eisentraut(at)2ndquadrant(dot)com> writes: >\nok done msvc 2019 (64 bits), is worried about it:https://github.com/postgres/postgres/commit/0aa8f764088ea0f36620ae2955fa6c54ec736c46\"C:\\dll\\postgres\\pgsql.sln\" (default target) (1) ->\"C:\\dll\\postgres\\cyrillic_and_mic.vcxproj\" (default target) (37) ->\"C:\\dll\\postgres\\postgres.vcxproj\" (default target) (38) ->(ClCompile target) ->  C:\\dll\\postgres\\src\\backend\\utils\\adt\\dbsize.c(630,20): warning C4334: '<<': resultado de 32-bit shift convertido implicitamente para 64 bits (64-bit shift era pretendido?) [C:\\dll\\postgres\\postgres.vcxproj]    1 Warning(s)    0 Error(s)\"result of 32-bit shift implicitly converted to 64 bits (was 64-bit shift intended?)\"regards,Ranier Vilela", "msg_date": "Mon, 14 Sep 2020 15:11:01 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Since '2001-09-09 01:46:40'::timestamp microseconds are lost when\n extracting epoch" }, { "msg_contents": "Ranier Vilela <ranier.vf@gmail.com> writes:\n> msvc 2019 (64 bits), is worried about it:\n> C:\\dll\\postgres\\src\\backend\\utils\\adt\\dbsize.c(630,20): warning C4334:\n> '<<': resultado de 32-bit shift convertido implicitamente para 64 bits\n> (64-bit shift era pretendid\n> o?) [C:\\dll\\postgres\\postgres.vcxproj]\n\nYeah, most/all of the MSVC buildfarm members are showing this warning too.\nThe previous coding was\n\n\tInt64GetDatum((int64) (1 << count))\n\nwhich apparently is enough to silence MSVC, though it makes no difference\nas to the actual overflow risk involved.\n\nI'm a bit inclined to make the new code be\n\n\tNumericGetDatum(int64_to_numeric(INT64CONST(1) << count));\n\nie do the shift in 64 bits. That's either free or next door to free, and\nit allows larger count values to be accepted. The existing callers don't\ncare of course, but someday somebody might try to expose this function\nmore widely.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 14 Sep 2020 14:33:53 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Since '2001-09-09 01:46:40'::timestamp microseconds are lost when\n extracting epoch" }, { "msg_contents": "Em seg., 14 de set. de 2020 às 15:33, Tom Lane <tgl@sss.pgh.pa.us> escreveu:\n\n> Ranier Vilela <ranier.vf@gmail.com> writes:\n> > msvc 2019 (64 bits), is worried about it:\n> > C:\\dll\\postgres\\src\\backend\\utils\\adt\\dbsize.c(630,20): warning C4334:\n> > '<<': resultado de 32-bit shift convertido implicitamente para 64 bits\n> > (64-bit shift era pretendid\n> > o?) [C:\\dll\\postgres\\postgres.vcxproj]\n>\n> Yeah, most/all of the MSVC buildfarm members are showing this warning too.\n> The previous coding was\n>\n> Int64GetDatum((int64) (1 << count))\n>\n> which apparently is enough to silence MSVC, though it makes no difference\n> as to the actual overflow risk involved.\n>\n> I'm a bit inclined to make the new code be\n>\n> NumericGetDatum(int64_to_numeric(INT64CONST(1) << count));\n>\n+1\nmsvc 2019 (64 bits), is happy with INT64CONST(1)\n\nregards,\nRanier Vilela\n\nEm seg., 14 de set. de 2020 às 15:33, Tom Lane <tgl@sss.pgh.pa.us> escreveu:Ranier Vilela <ranier.vf@gmail.com> writes:\n> msvc 2019 (64 bits), is worried about it:\n>   C:\\dll\\postgres\\src\\backend\\utils\\adt\\dbsize.c(630,20): warning C4334:\n> '<<': resultado de 32-bit shift convertido implicitamente para 64 bits\n> (64-bit shift era pretendid\n> o?) [C:\\dll\\postgres\\postgres.vcxproj]\n\nYeah, most/all of the MSVC buildfarm members are showing this warning too.\nThe previous coding was\n\n        Int64GetDatum((int64) (1 << count))\n\nwhich apparently is enough to silence MSVC, though it makes no difference\nas to the actual overflow risk involved.\n\nI'm a bit inclined to make the new code be\n\n        NumericGetDatum(int64_to_numeric(INT64CONST(1) << count));+1msvc 2019 (64 bits), is happy with INT64CONST(1)regards,Ranier Vilela", "msg_date": "Mon, 14 Sep 2020 15:53:48 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Since '2001-09-09 01:46:40'::timestamp microseconds are lost when\n extracting epoch" } ]
[ { "msg_contents": "pg_dump et al have some low-level debug log messages that commit\ncc8d41511 converted to pg_log_debug() calls, replacing the previous\none-off logging verbosity system that was there. However, these\ncalls are dead code as things stand, because there is no way to set\n__pg_log_level high enough to get them to print.\n\nI propose the attached minimal patch to restore the previous\nfunctionality.\n\nAlternatively, we might consider inventing an additional logging.c\nfunction pg_logging_increase_level() with the obvious semantics, and\nmake the various programs just call that when they see a -v switch.\nThat would be a slightly bigger patch, but it would more easily support\nprograms with a range of useful verbosities, so maybe that's a better\nidea.\n\nIn a quick look around, I could not find any other unreachable\npg_log_debug calls.\n\n(Note: it seems possible that the theoretical multiple verbosity\nlevels in pg_dump were already broken before cc8d41511, because\nright offhand I do not see any code that that removed that would\nhave allowed invoking the higher levels either. Nonetheless, there\nis no point in carrying dead code --- and these messages *are*\nof some interest. I discovered this problem while trying to\ndebug parallel pg_restore behavior just now, and wondering\nwhy \"-v -v\" didn't produce the messages I saw in the source code.)\n\n\t\t\tregards, tom lane", "msg_date": "Mon, 14 Sep 2020 16:50:25 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "\"Unified logging system\" breaks access to pg_dump debug outputs" }, { "msg_contents": "I wrote:\n> Alternatively, we might consider inventing an additional logging.c\n> function pg_logging_increase_level() with the obvious semantics, and\n> make the various programs just call that when they see a -v switch.\n> That would be a slightly bigger patch, but it would more easily support\n> programs with a range of useful verbosities, so maybe that's a better\n> idea.\n\nAfter further thought, I concluded that's a clearly superior solution,\nso 0001 attached does it like that. After noting that the enum values\nare in the opposite direction from how I thought they went, I realized\nthat \"increase_level\" might be a bit ambiguous, so I now propose to\ncall it pg_logging_increase_verbosity.\n\n> (Note: it seems possible that the theoretical multiple verbosity\n> levels in pg_dump were already broken before cc8d41511, because\n> right offhand I do not see any code that that removed that would\n> have allowed invoking the higher levels either.\n\nCloser inspection says this was almost certainly true, because\nI discovered that pg_dump -v -v crashes if you don't specify\nan output filename :-(. So this has probably been unreachable\nat least since we went over to using our own snprintf always;\nbefore that, depending on platform, it might've been fine.\nSo we also need 0002 attached to fix that.\n\n\t\t\tregards, tom lane", "msg_date": "Tue, 15 Sep 2020 12:59:13 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: \"Unified logging system\" breaks access to pg_dump debug outputs" }, { "msg_contents": "On 2020-Sep-15, Tom Lane wrote:\n\n> I wrote:\n> > Alternatively, we might consider inventing an additional logging.c\n> > function pg_logging_increase_level() with the obvious semantics, and\n> > make the various programs just call that when they see a -v switch.\n> > That would be a slightly bigger patch, but it would more easily support\n> > programs with a range of useful verbosities, so maybe that's a better\n> > idea.\n> \n> After further thought, I concluded that's a clearly superior solution,\n> so 0001 attached does it like that. After noting that the enum values\n> are in the opposite direction from how I thought they went, I realized\n> that \"increase_level\" might be a bit ambiguous, so I now propose to\n> call it pg_logging_increase_verbosity.\n\nI like this better too ... I've wished for extra-verbose messages from\npg_dump in the past, and this now allows me to add something should I\nwant them again.\n\n> > (Note: it seems possible that the theoretical multiple verbosity\n> > levels in pg_dump were already broken before cc8d41511, because\n> > right offhand I do not see any code that that removed that would\n> > have allowed invoking the higher levels either.\n> \n> Closer inspection says this was almost certainly true, because\n> I discovered that pg_dump -v -v crashes if you don't specify\n> an output filename :-(. So this has probably been unreachable\n> at least since we went over to using our own snprintf always;\n> before that, depending on platform, it might've been fine.\n> So we also need 0002 attached to fix that.\n\nUgh.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 15 Sep 2020 18:38:15 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: \"Unified logging system\" breaks access to pg_dump debug outputs" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> On 2020-Sep-15, Tom Lane wrote:\n>> After further thought, I concluded that's a clearly superior solution,\n>> so 0001 attached does it like that. After noting that the enum values\n>> are in the opposite direction from how I thought they went, I realized\n>> that \"increase_level\" might be a bit ambiguous, so I now propose to\n>> call it pg_logging_increase_verbosity.\n\n> I like this better too ... I've wished for extra-verbose messages from\n> pg_dump in the past, and this now allows me to add something should I\n> want them again.\n\nPushed, thanks for reviewing.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 17 Sep 2020 12:53:38 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: \"Unified logging system\" breaks access to pg_dump debug outputs" } ]
[ { "msg_contents": "Hi, hackers\n\nFor now, postgres use single process to send, receive and replay the WAL when we use stream replication,\nis there any point to parallelize this process? If it does, how do we start?\n\nAny thoughts?\n\nBest regards\n\nJapin Li\n\n", "msg_date": "Tue, 15 Sep 2020 03:56:53 +0000", "msg_from": "Li Japin <japinli@hotmail.com>", "msg_from_op": true, "msg_subject": "Parallelize stream replication process" }, { "msg_contents": "On Tue, Sep 15, 2020 at 9:27 AM Li Japin <japinli@hotmail.com> wrote:\n>\n> For now, postgres use single process to send, receive and replay the WAL when we use stream replication,\n> is there any point to parallelize this process? If it does, how do we start?\n>\n> Any thoughts?\n>\n\nI think we must ask few questions:\n\n1. What's the major gain we get out of this? Is it that the time to\nstream gets reduced or something else?\nIf the answer to the above point is something solid, then\n2. How do we distribute the work to multiple processes?\n3. Do we need all of the workers to maintain the order in which they\nread WAL files(on the publisher) and apply the changes(on the\nsubscriber?)\n3. Do we want to map the sender/publisher workers to\nreceiver/subscriber workers on a one-to-one basis? If not, how do we\ndo it?\n4. How do sender and receiver workers communicate?\n5. What if we have multiple subscribers/receivers?\n\nI'm no expert in replication, I may be wrong as well. Others may have\nbetter thoughts.\n\nWith Regards,\nBharath Rupireddy.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 15 Sep 2020 10:11:00 +0530", "msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Parallelize stream replication process" }, { "msg_contents": "\n\nOn 2020/09/15 13:41, Bharath Rupireddy wrote:\n> On Tue, Sep 15, 2020 at 9:27 AM Li Japin <japinli@hotmail.com> wrote:\n>>\n>> For now, postgres use single process to send, receive and replay the WAL when we use stream replication,\n>> is there any point to parallelize this process? If it does, how do we start?\n>>\n>> Any thoughts?\n\nProbably this is another parallelism than what you're thinking,\nbut I was thinking to start up walwriter process in the standby server\nand make it fsync the streamed WAL data. This means that we leave\na part of tasks of walreceiver process to walwriter. Walreceiver\nperforms WAL receive and write, and walwriter performs WAL flush,\nin parallel. I'm just expecting that this change would improve\nthe replication performance, e.g., reduce the time to wait for\nsync replication.\n\nWithout this change (i.e., originally), only walreceiver performs\nWAL receive, write and flush. So wihle walreceiver is fsyncing WAL data,\nit cannot receive newly-arrived WAL data. If WAL flush takes a time,\nwhich means that the time to wait for sync replication in the primary\nwould be enlarged.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Tue, 15 Sep 2020 16:41:33 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Parallelize stream replication process" }, { "msg_contents": "Thanks for clarifying the questions!\n\n> On Sep 15, 2020, at 12:41 PM, Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com> wrote:\n> \n> On Tue, Sep 15, 2020 at 9:27 AM Li Japin <japinli@hotmail.com> wrote:\n>> \n>> For now, postgres use single process to send, receive and replay the WAL when we use stream replication,\n>> is there any point to parallelize this process? If it does, how do we start?\n>> \n>> Any thoughts?\n>> \n> \n> I think we must ask few questions:\n> \n> 1. What's the major gain we get out of this? Is it that the time to\n> stream gets reduced or something else?\n\nI think when the database failover, we might shorten the recovery time from the parallel stream replication.\n\n> If the answer to the above point is something solid, then\n> 2. How do we distribute the work to multiple processes?\n> 3. Do we need all of the workers to maintain the order in which they\n> read WAL files(on the publisher) and apply the changes(on the\n> subscriber?)\n> 3. Do we want to map the sender/publisher workers to\n> receiver/subscriber workers on a one-to-one basis? If not, how do we\n> do it?\n> 4. How do sender and receiver workers communicate?\n> 5. What if we have multiple subscribers/receivers?\n> \n> I'm no expert in replication, I may be wrong as well. Others may have\n> better thoughts.\n> \n\nMaybe we can distribute the work to multiple processes according by the WAL record type.\n\nIn the first step, I think we can parallel the replay process. We can classify the WAL by WAL type or RmgrId,\nand then parallel those WAL replay if possible.\n\nThen, we can think how to parallel WalReceiver and WalSender.\n\nBest regards\nJapin Li.\n\n\n\n\n", "msg_date": "Wed, 16 Sep 2020 03:02:20 +0000", "msg_from": "Li Japin <japinli@hotmail.com>", "msg_from_op": true, "msg_subject": "Re: Parallelize stream replication process" }, { "msg_contents": "\r\n\r\n> On Sep 15, 2020, at 3:41 PM, Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\r\n> \r\n> \r\n> \r\n> On 2020/09/15 13:41, Bharath Rupireddy wrote:\r\n>> On Tue, Sep 15, 2020 at 9:27 AM Li Japin <japinli@hotmail.com> wrote:\r\n>>> \r\n>>> For now, postgres use single process to send, receive and replay the WAL when we use stream replication,\r\n>>> is there any point to parallelize this process? If it does, how do we start?\r\n>>> \r\n>>> Any thoughts?\r\n> \r\n> Probably this is another parallelism than what you're thinking,\r\n> but I was thinking to start up walwriter process in the standby server\r\n> and make it fsync the streamed WAL data. This means that we leave\r\n> a part of tasks of walreceiver process to walwriter. Walreceiver\r\n> performs WAL receive and write, and walwriter performs WAL flush,\r\n> in parallel. I'm just expecting that this change would improve\r\n> the replication performance, e.g., reduce the time to wait for\r\n> sync replication.\r\n> \r\n> Without this change (i.e., originally), only walreceiver performs\r\n> WAL receive, write and flush. So wihle walreceiver is fsyncing WAL data,\r\n> it cannot receive newly-arrived WAL data. If WAL flush takes a time,\r\n> which means that the time to wait for sync replication in the primary\r\n> would be enlarged.\r\n> \r\n> Regards,\r\n> \r\n> -- \r\n> Fujii Masao\r\n> Advanced Computing Technology Center\r\n> Research and Development Headquarters\r\n> NTT DATA CORPORATION\r\n\r\nYeah, this might be a direction. \r\n\r\nNow I am thinking about how to parallel WAL log replay. If we can improve the efficiency\r\nof replay, then we can shorten the database recovery time (streaming replication or database\r\ncrash recovery). \r\n\r\nFor streaming replication, we may need to improve the transmission of WAL logs to improve\r\nthe entire recovery process.\r\n\r\nI’m not sure if this is correct.\r\n\r\nRegards,\r\nJapin Li.\r\n\r\n", "msg_date": "Wed, 16 Sep 2020 03:15:38 +0000", "msg_from": "Li Japin <japinli@hotmail.com>", "msg_from_op": true, "msg_subject": "Re: Parallelize stream replication process" }, { "msg_contents": "\r\n\r\n> On Sep 16, 2020, at 11:15 AM, Li Japin <japinli@hotmail.com> wrote:\r\n> \r\n> \r\n> \r\n>> On Sep 15, 2020, at 3:41 PM, Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\r\n>> \r\n>> \r\n>> \r\n>> On 2020/09/15 13:41, Bharath Rupireddy wrote:\r\n>>> On Tue, Sep 15, 2020 at 9:27 AM Li Japin <japinli@hotmail.com> wrote:\r\n>>>> \r\n>>>> For now, postgres use single process to send, receive and replay the WAL when we use stream replication,\r\n>>>> is there any point to parallelize this process? If it does, how do we start?\r\n>>>> \r\n>>>> Any thoughts?\r\n>> \r\n>> Probably this is another parallelism than what you're thinking,\r\n>> but I was thinking to start up walwriter process in the standby server\r\n>> and make it fsync the streamed WAL data. This means that we leave\r\n>> a part of tasks of walreceiver process to walwriter. Walreceiver\r\n>> performs WAL receive and write, and walwriter performs WAL flush,\r\n>> in parallel. I'm just expecting that this change would improve\r\n>> the replication performance, e.g., reduce the time to wait for\r\n>> sync replication.\r\n\r\nYes this should be able to improve that in theory. \r\n\r\n>> \r\n>> Without this change (i.e., originally), only walreceiver performs\r\n>> WAL receive, write and flush. So wihle walreceiver is fsyncing WAL data,\r\n>> it cannot receive newly-arrived WAL data. If WAL flush takes a time,\r\n>> which means that the time to wait for sync replication in the primary\r\n>> would be enlarged.\r\n>> \r\n>> Regards,\r\n>> \r\n>> -- \r\n>> Fujii Masao\r\n>> Advanced Computing Technology Center\r\n>> Research and Development Headquarters\r\n>> NTT DATA CORPORATION\r\n> \r\n> Yeah, this might be a direction. \r\n> \r\n> Now I am thinking about how to parallel WAL log replay. If we can improve the efficiency\r\n> of replay, then we can shorten the database recovery time (streaming replication or database\r\n> crash recovery). \r\n\r\nYes, parallelization should be able to help the scenario that cpu util rate is 100% or if it is not\r\n100% but continues blocking in some operations which could be improved by running in\r\nparallel. There are a lot of scenarios of WAL replay (memory operation, system calls, locking, etc).\r\nI do not have the experience of real production environment, so not sure whether or how\r\nthe recovery suffer, but I believe parallel recovery should help to accelerate and help failover\r\nwhich is quite important especially in cloud environment. To do this may need to carefully\r\nanalyze the dependency of various WALL at first. It won’t be a small effort. I’ve heard some\r\ndatabases have implemented this though not sure how much that helps.\r\n\r\nFor parallel wal receiver/sender, its functionality is simple so after decoupling the fsync operation to\r\na separate process not sure how beneficial parallelization would be (surely if wal receiver/sender\r\nIs 100% cpu utilized that is needed).\r\n\r\n\r\n> \r\n> For streaming replication, we may need to improve the transmission of WAL logs to improve\r\n> the entire recovery process.\r\n> \r\n> I’m not sure if this is correct.\r\n> \r\n> Regards,\r\n> Japin Li.\r\n> \r\n\r\n", "msg_date": "Wed, 16 Sep 2020 05:46:03 +0000", "msg_from": "Paul Guo <guopa@vmware.com>", "msg_from_op": false, "msg_subject": "Re: Parallelize stream replication process" }, { "msg_contents": "\n\n> On 16-Sep-2020, at 8:32 AM, Li Japin <japinli@hotmail.com> wrote:\n> \n> Thanks for clarifying the questions!\n> \n>> On Sep 15, 2020, at 12:41 PM, Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com> wrote:\n>> \n>> I think we must ask few questions:\n>> \n>> 1. What's the major gain we get out of this? Is it that the time to\n>> stream gets reduced or something else?\n> \n> I think when the database failover, we might shorten the recovery time from the parallel stream replication.\n> \n>> If the answer to the above point is something solid, then\n>> 2. How do we distribute the work to multiple processes?\n>> 3. Do we need all of the workers to maintain the order in which they\n>> read WAL files(on the publisher) and apply the changes(on the\n>> subscriber?)\n>> 3. Do we want to map the sender/publisher workers to\n>> receiver/subscriber workers on a one-to-one basis? If not, how do we\n>> do it?\n>> 4. How do sender and receiver workers communicate?\n>> 5. What if we have multiple subscribers/receivers?\n>> \n>> I'm no expert in replication, I may be wrong as well. Others may have\n>> better thoughts.\n>> \n> \n> Maybe we can distribute the work to multiple processes according by the WAL record type.\n> \n> In the first step, I think we can parallel the replay process. We can classify the WAL by WAL type or RmgrId,\n> and then parallel those WAL replay if possible.\n> \n\nThis is a rather hard problem to solve, mainly because the (partial)\norder inherent in the WAL stream must be preserved when distributing\nsubsets of WAL records for parallel replay. The order can be\ncharacterised as follows:\n\n(1) All records emitted by a transaction must be replayed before\nreplaying the commit record emitted by that transaction.\n\n(2) Commit records emitted by different transactions must be replayed\nin the order in which they appear in the WAL stream.\n\nAsim\n\n", "msg_date": "Wed, 16 Sep 2020 11:43:14 +0000", "msg_from": "Asim Praveen <pasim@vmware.com>", "msg_from_op": false, "msg_subject": "Re: Parallelize stream replication process" }, { "msg_contents": "Li Japin wrote:\n\n> If we can improve the efficiency of replay, then we can shorten the database recovery time (streaming replication or database crash recovery). \n(..)\n> For streaming replication, we may need to improve the transmission of WAL logs to improve the entire recovery process.\n> I’m not sure if this is correct.\n\nHi, \n\nIf you are interested in increased efficiency of WAL replay internals/startup performance then you might be interested in following threads:\n\nCache relation sizes in recovery - https://www.postgresql.org/message-id/flat/CA%2BhUKG%2BNPZeEdLXAcNr%2Bw0YOZVb0Un0_MwTBpgmmVDh7No2jbg%40mail.gmail.com#feace7ccbb8e3df8b086d0a2217df91f\nFaster compactify_tuples() - https://www.postgresql.org/message-id/flat/CA+hUKGKMQFVpjr106gRhwk6R-nXv0qOcTreZuQzxgpHESAL6dw@mail.gmail.com\nHanding off SLRU fsyncs to the checkpointer - https://www.postgresql.org/message-id/flat/CA%2BhUKGLJ%3D84YT%2BNvhkEEDAuUtVHMfQ9i-N7k_o50JmQ6Rpj_OQ%40mail.gmail.com\nOptimizing compactify_tuples() - https://www.postgresql.org/message-id/flat/CA%2BhUKGKMQFVpjr106gRhwk6R-nXv0qOcTreZuQzxgpHESAL6dw%40mail.gmail.com\nBackground bgwriter during crash recovery - https://www.postgresql.org/message-id/flat/CA+hUKGJ8NRsqgkZEnsnRc2MFROBV-jCnacbYvtpptK2A9YYp9Q@mail.gmail.com\nWIP: WAL prefetch (another approach) - https://www.postgresql.org/message-id/flat/CA%2BhUKGJ4VJN8ttxScUFM8dOKX0BrBiboo5uz1cq%3DAovOddfHpA%40mail.gmail.com\nDivision in dynahash.c due to HASH_FFACTOR - https://www.postgresql.org/message-id/flat/VI1PR0701MB696044FC35013A96FECC7AC8F62D0%40VI1PR0701MB6960.eurprd07.prod.outlook.com\n[PATCH] guc-ify the formerly hard-coded MAX_SEND_SIZE to max_wal_send - https://www.postgresql.org/message-id/flat/CACJqAM2uAUnEAy0j2RRJOSM1UHPdGxCr%3DU-HbqEf0aAcdhUoEQ%40mail.gmail.com\nUnnecessary delay in streaming replication due to replay lag - https://www.postgresql.org/message-id/flat/CANXE4Tc3FNvZ_xAimempJWv_RH9pCvsZH7Yq93o1VuNLjUT-mQ%40mail.gmail.com\nWAL prefetching in future combined with AIO (IO_URING) - longer term future, https://anarazel.de/talks/2020-05-28-pgcon-aio/2020-05-28-pgcon-aio.pdf\n\nGood way to start is to profile the system what is taking time during Your failover situation OR Your normal hot-standby behavior \nand then proceed to identifying and characterizing the main bottleneck - there can be many depending on the situation (inefficient single processes PostgreSQL code, \nCPU-bound startup/recovering, IOPS/VFS/ syscall/s / API limitations, single TCP stream limitations single TCP stream latency impact in WAN, contention on locks in hot-standby case...) .\n\nSome of the above are already commited in for 14/master, some are not and require further discussions and testing. \nWithout real identification of the bottleneck and WAL stream statistics you are facing , it's hard to say how would parallel WAL recovery improve the situation.\n\n-J.\n\n\n", "msg_date": "Thu, 17 Sep 2020 13:18:55 +0000", "msg_from": "Jakub Wartak <Jakub.Wartak@tomtom.com>", "msg_from_op": false, "msg_subject": "Re: Parallelize stream replication process" }, { "msg_contents": "Thanks for your advice! This help me a lot.\r\n\r\n> On Sep 17, 2020, at 9:18 PM, Jakub Wartak <Jakub.Wartak@tomtom.com> wrote:\r\n> \r\n> Li Japin wrote:\r\n> \r\n>> If we can improve the efficiency of replay, then we can shorten the database recovery time (streaming replication or database crash recovery). \r\n> (..)\r\n>> For streaming replication, we may need to improve the transmission of WAL logs to improve the entire recovery process.\r\n>> I’m not sure if this is correct.\r\n> \r\n> Hi, \r\n> \r\n> If you are interested in increased efficiency of WAL replay internals/startup performance then you might be interested in following threads:\r\n> \r\n> Cache relation sizes in recovery - https://www.postgresql.org/message-id/flat/CA%2BhUKG%2BNPZeEdLXAcNr%2Bw0YOZVb0Un0_MwTBpgmmVDh7No2jbg%40mail.gmail.com#feace7ccbb8e3df8b086d0a2217df91f\r\n> Faster compactify_tuples() - https://www.postgresql.org/message-id/flat/CA+hUKGKMQFVpjr106gRhwk6R-nXv0qOcTreZuQzxgpHESAL6dw@mail.gmail.com\r\n> Handing off SLRU fsyncs to the checkpointer - https://www.postgresql.org/message-id/flat/CA%2BhUKGLJ%3D84YT%2BNvhkEEDAuUtVHMfQ9i-N7k_o50JmQ6Rpj_OQ%40mail.gmail.com\r\n> Optimizing compactify_tuples() - https://www.postgresql.org/message-id/flat/CA%2BhUKGKMQFVpjr106gRhwk6R-nXv0qOcTreZuQzxgpHESAL6dw%40mail.gmail.com\r\n> Background bgwriter during crash recovery - https://www.postgresql.org/message-id/flat/CA+hUKGJ8NRsqgkZEnsnRc2MFROBV-jCnacbYvtpptK2A9YYp9Q@mail.gmail.com\r\n> WIP: WAL prefetch (another approach) - https://www.postgresql.org/message-id/flat/CA%2BhUKGJ4VJN8ttxScUFM8dOKX0BrBiboo5uz1cq%3DAovOddfHpA%40mail.gmail.com\r\n> Division in dynahash.c due to HASH_FFACTOR - https://www.postgresql.org/message-id/flat/VI1PR0701MB696044FC35013A96FECC7AC8F62D0%40VI1PR0701MB6960.eurprd07.prod.outlook.com\r\n> [PATCH] guc-ify the formerly hard-coded MAX_SEND_SIZE to max_wal_send - https://www.postgresql.org/message-id/flat/CACJqAM2uAUnEAy0j2RRJOSM1UHPdGxCr%3DU-HbqEf0aAcdhUoEQ%40mail.gmail.com\r\n> Unnecessary delay in streaming replication due to replay lag - https://www.postgresql.org/message-id/flat/CANXE4Tc3FNvZ_xAimempJWv_RH9pCvsZH7Yq93o1VuNLjUT-mQ%40mail.gmail.com\r\n> WAL prefetching in future combined with AIO (IO_URING) - longer term future, https://anarazel.de/talks/2020-05-28-pgcon-aio/2020-05-28-pgcon-aio.pdf\r\n> \r\n> Good way to start is to profile the system what is taking time during Your failover situation OR Your normal hot-standby behavior \r\n> and then proceed to identifying and characterizing the main bottleneck - there can be many depending on the situation (inefficient single processes PostgreSQL code, \r\n> CPU-bound startup/recovering, IOPS/VFS/ syscall/s / API limitations, single TCP stream limitations single TCP stream latency impact in WAN, contention on locks in hot-standby case...) .\r\n> \r\n> Some of the above are already commited in for 14/master, some are not and require further discussions and testing. \r\n> Without real identification of the bottleneck and WAL stream statistics you are facing , it's hard to say how would parallel WAL recovery improve the situation.\r\n> \r\n> -J.\r\n\r\n", "msg_date": "Fri, 18 Sep 2020 03:00:14 +0000", "msg_from": "Li Japin <japinli@hotmail.com>", "msg_from_op": true, "msg_subject": "Re: Parallelize stream replication process" } ]
[ { "msg_contents": "Existing code uses various inconsistent ways to printf struct stat's \nst_size member. The type of that is off_t, which is in most cases a \nsigned 64-bit integer, so use the long long int format for it.\n\nI don't think anything is affected by this in practice, but it seems \nreasonable to set a good convention for the next time this code gets copied.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Tue, 15 Sep 2020 13:38:30 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Standardize the printf format for st_size" } ]
[ { "msg_contents": "Hi,\n\nBased on a couple of independent reports from users with no idea how\nto judge the progress of a system recovering from a crash, Christoph\nand I wondered if we should override update_process_title for the\n\"recovering ...\" message, at least until connections are allowed. We\nalready do that to set the initial titles.\n\nCrash recovery is a rare case where important information is reported\nthrough the process title that isn't readily available anywhere else,\nsince you can't log in. If you want to gauge progress on a system\nthat happened to crash with update_process_title set to off, your best\nhope is probably to trace the process or spy on the files it has open,\nto see which WAL segment it's accessing, but that's not very nice.\n\n\n", "msg_date": "Wed, 16 Sep 2020 00:10:18 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Force update_process_title=on in crash recovery?" }, { "msg_contents": "Thomas Munro <thomas.munro@gmail.com> writes:\n> Based on a couple of independent reports from users with no idea how\n> to judge the progress of a system recovering from a crash, Christoph\n> and I wondered if we should override update_process_title for the\n> \"recovering ...\" message, at least until connections are allowed. We\n> already do that to set the initial titles.\n\n> Crash recovery is a rare case where important information is reported\n> through the process title that isn't readily available anywhere else,\n> since you can't log in. If you want to gauge progress on a system\n> that happened to crash with update_process_title set to off, your best\n> hope is probably to trace the process or spy on the files it has open,\n> to see which WAL segment it's accessing, but that's not very nice.\n\nSeems like a good argument, but you'd have to be careful about the\nfinal state when you stop overriding update_process_title --- it can't\nbe left looking like it's still-in-progress on some random WAL file.\n(Compare my nearby gripes about walsenders being sloppy about their\npg_stat_activity and process title presentations.)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 15 Sep 2020 10:01:18 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Force update_process_title=on in crash recovery?" }, { "msg_contents": "On Tue, Sep 15, 2020 at 10:01:18AM -0400, Tom Lane wrote:\n> Thomas Munro <thomas.munro@gmail.com> writes:\n> > Based on a couple of independent reports from users with no idea how\n> > to judge the progress of a system recovering from a crash, Christoph\n> > and I wondered if we should override update_process_title for the\n> > \"recovering ...\" message, at least until connections are allowed. We\n> > already do that to set the initial titles.\n> \n> > Crash recovery is a rare case where important information is reported\n> > through the process title that isn't readily available anywhere else,\n> > since you can't log in. If you want to gauge progress on a system\n> > that happened to crash with update_process_title set to off, your best\n> > hope is probably to trace the process or spy on the files it has open,\n> > to see which WAL segment it's accessing, but that's not very nice.\n> \n> Seems like a good argument, but you'd have to be careful about the\n> final state when you stop overriding update_process_title --- it can't\n> be left looking like it's still-in-progress on some random WAL file.\n> (Compare my nearby gripes about walsenders being sloppy about their\n> pg_stat_activity and process title presentations.)\n\nRelated:\nhttps://commitfest.postgresql.org/29/2688/\n\nI'm not sure I understood Michael's recent message, but I think maybe refers to\npromotion of a standby.\n\n-- \nJustin\n\n\n", "msg_date": "Tue, 15 Sep 2020 15:07:50 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Force update_process_title=on in crash recovery?" }, { "msg_contents": "On Tue, Sep 15, 2020 at 10:01:18AM -0400, Tom Lane wrote:\n> Seems like a good argument, but you'd have to be careful about the\n> final state when you stop overriding update_process_title --- it can't\n> be left looking like it's still-in-progress on some random WAL file.\n> (Compare my nearby gripes about walsenders being sloppy about their\n> pg_stat_activity and process title presentations.)\n\nAnother thing to be careful here is WIN32, see 0921554. And slowing\ndown recovery is never a good idea.\n--\nMichael", "msg_date": "Wed, 16 Sep 2020 11:30:06 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Force update_process_title=on in crash recovery?" }, { "msg_contents": "On Wed, Sep 16, 2020 at 2:30 PM Michael Paquier <michael@paquier.xyz> wrote:\n> On Tue, Sep 15, 2020 at 10:01:18AM -0400, Tom Lane wrote:\n> > Seems like a good argument, but you'd have to be careful about the\n> > final state when you stop overriding update_process_title --- it can't\n> > be left looking like it's still-in-progress on some random WAL file.\n> > (Compare my nearby gripes about walsenders being sloppy about their\n> > pg_stat_activity and process title presentations.)\n>\n> Another thing to be careful here is WIN32, see 0921554. And slowing\n> down recovery is never a good idea.\n\nRight, that commit makes a lot of sense because it suppresses many\nsystem calls that happen for each query. The same problem existed on\nolder FreeBSD versions and I saw that costing ~10% of TPS on read-only\npgbench. In other commits I've been removing system calls that happen\nfor every WAL record. But in this thread I'm talking about an update\nper 16MB WAL file, which seems like an acceptable ratio to me.\n\n\n", "msg_date": "Wed, 16 Sep 2020 17:24:01 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Force update_process_title=on in crash recovery?" }, { "msg_contents": "Thomas Munro <thomas.munro@gmail.com> writes:\n> On Wed, Sep 16, 2020 at 2:30 PM Michael Paquier <michael@paquier.xyz> wrote:\n>> Another thing to be careful here is WIN32, see 0921554. And slowing\n>> down recovery is never a good idea.\n\n> Right, that commit makes a lot of sense because it suppresses many\n> system calls that happen for each query. The same problem existed on\n> older FreeBSD versions and I saw that costing ~10% of TPS on read-only\n> pgbench. In other commits I've been removing system calls that happen\n> for every WAL record. But in this thread I'm talking about an update\n> per 16MB WAL file, which seems like an acceptable ratio to me.\n\nHmm ... the thread leading up to 0921554 indicates that the performance\npenalty of update_process_title=on is just ridiculously large on Windows.\nMaybe those numbers are not relevant to crash recovery WAL-application,\nbut it might be smart to actually measure that not just assume it.\n\nIn any case, I'd recommend setting up any patch you create for this\nto be easily \"ifndef WIN32\"'d in case we change our minds on the\npoint later.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 16 Sep 2020 01:43:32 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Force update_process_title=on in crash recovery?" }, { "msg_contents": "On Wed, 16 Sep 2020 at 17:43, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Hmm ... the thread leading up to 0921554 indicates that the performance\n> penalty of update_process_title=on is just ridiculously large on Windows.\n> Maybe those numbers are not relevant to crash recovery WAL-application,\n> but it might be smart to actually measure that not just assume it.\n\nI had a go at measuring this on Windows and couldn't really detect any\nslowdown from running update_process_title on vs off. Average over 3\nruns with update_process_title = off was 94.38 s, switched on the\naverage was 93.81 s. (Some noise there)\n\nAdding a bit of logging shows that the process title was set 225\ntimes. Once setting it to an empty string then once for each of the\n224 segments replayed.\n\nAlso, from a pgbench -s test with update_process_title on and again\nwith off I see 9343 tps vs 11969 tps. The process title is changed\ntwice for each query, once to set it to the query and once to set it\nto \"idle\". Doing a bit of maths there is seems that setting the\nprocess title takes about 15 microseconds per call. So it would have\ntaken about 3.38 milliseconds to set the process title 225 times for\nrecovery, or if you prefer, 0.003609% additional overhead.\n\nI don't think we'll notice.\n\nDavid", "msg_date": "Thu, 17 Sep 2020 18:43:37 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Force update_process_title=on in crash recovery?" } ]
[ { "msg_contents": "Hi,\n\nAttached is a draft of the PostgreSQL 13 RC 1 release announcement.\n\nIf you have feedback, please be sure you've left it no later than\n2020-09-16 AoE.\n\nThanks!\n\nJonathan", "msg_date": "Tue, 15 Sep 2020 12:10:08 -0400", "msg_from": "\"Jonathan S. Katz\" <jkatz@postgresql.org>", "msg_from_op": true, "msg_subject": "PostgreSQL 13 RC 1 release announcement draft" }, { "msg_contents": "On 2020-09-15 18:10, Jonathan S. Katz wrote:\n> To upgrade to PostgreSQL 13 RC 1 from Beta 3 or an earlier version of\n> PostgreSQL 13, you will need to use a strategy similar to upgrading between\n> major versions of PostgreSQL (e.g. `pg_upgrade` or `pg_dump` / `pg_restore`).\n\nIs this correct? I don't see a catversion change between beta3 and rc1.\n\nAlso, if correct, the word \"similar\" seems redundant or confusing here.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 16 Sep 2020 07:08:22 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: PostgreSQL 13 RC 1 release announcement draft" }, { "msg_contents": "On 9/16/20 1:08 AM, Peter Eisentraut wrote:\n> On 2020-09-15 18:10, Jonathan S. Katz wrote:\n>> To upgrade to PostgreSQL 13 RC 1 from Beta 3 or an earlier version of\n>> PostgreSQL 13, you will need to use a strategy similar to upgrading\n>> between\n>> major versions of PostgreSQL (e.g. `pg_upgrade` or `pg_dump` /\n>> `pg_restore`).\n> \n> Is this correct?  I don't see a catversion change between beta3 and rc1.\n\nWe've typically recommended doing the pg_upgrade since they may be\ncoming from a version with a lower catversion. I can change \"you will\nneed\" to \"you may need\" to be more accurate, but then that leads to the\nquestion \"who may need?\".\n\nPerhaps the safest way to say it would be:\n\n\"To upgrade to PostgreSQL 13 RC 1 from Beta 3 or an earlier version of\nPostgreSQL 13, you may need to use a strategy for upgrading between\nmajor versions of PostgreSQL (e.g. `pg_upgrade` or `pg_dump` /\n`pg_restore`). If you are unsure of the upgrade strategy to use, we\nrecommend using the major version upgrade strategy.\"\n\n(Though, this is why when typically brought up, I leave it at need, as\nit's more succinct, and those who are typically upgrading between betas\n+ rcs tend to be more in the weeds anyway ;)\n\n> Also, if correct, the word \"similar\" seems redundant or confusing here.\n\nSo if we opt to keep the above language:\n\n\"To upgrade to PostgreSQL 13 RC 1 from Beta 3 or an earlier version of\nPostgreSQL 13, you will need to use a major version upgrade strategy,\ne.g. `pg_upgrade` or `pg_dump` / `pg_restore`.\"\n\nJonathan", "msg_date": "Wed, 16 Sep 2020 08:33:57 -0400", "msg_from": "\"Jonathan S. Katz\" <jkatz@postgresql.org>", "msg_from_op": true, "msg_subject": "Re: PostgreSQL 13 RC 1 release announcement draft" }, { "msg_contents": "On Wed, Sep 16, 2020 at 2:34 PM Jonathan S. Katz <jkatz@postgresql.org>\nwrote:\n\n> On 9/16/20 1:08 AM, Peter Eisentraut wrote:\n> > On 2020-09-15 18:10, Jonathan S. Katz wrote:\n> >> To upgrade to PostgreSQL 13 RC 1 from Beta 3 or an earlier version of\n> >> PostgreSQL 13, you will need to use a strategy similar to upgrading\n> >> between\n> >> major versions of PostgreSQL (e.g. `pg_upgrade` or `pg_dump` /\n> >> `pg_restore`).\n> >\n> > Is this correct? I don't see a catversion change between beta3 and rc1.\n>\n> We've typically recommended doing the pg_upgrade since they may be\n> coming from a version with a lower catversion. I can change \"you will\n> need\" to \"you may need\" to be more accurate, but then that leads to the\n> question \"who may need?\".\n>\n> Perhaps the safest way to say it would be:\n>\n> \"To upgrade to PostgreSQL 13 RC 1 from Beta 3 or an earlier version of\n> PostgreSQL 13, you may need to use a strategy for upgrading between\n> major versions of PostgreSQL (e.g. `pg_upgrade` or `pg_dump` /\n> `pg_restore`). If you are unsure of the upgrade strategy to use, we\n> recommend using the major version upgrade strategy.\"\n\n\n\n>\n> (Though, this is why when typically brought up, I leave it at need, as\n> it's more succinct, and those who are typically upgrading between betas\n> + rcs tend to be more in the weeds anyway ;)\n>\n> > Also, if correct, the word \"similar\" seems redundant or confusing here.\n>\n> So if we opt to keep the above language:\n>\n> \"To upgrade to PostgreSQL 13 RC 1 from Beta 3 or an earlier version of\n> PostgreSQL 13, you will need to use a major version upgrade strategy,\n> e.g. `pg_upgrade` or `pg_dump` / `pg_restore`.\"\n>\n\n Maybe something like:\n\nTo upgrade from beta <when was the last catversion change>, you will need\nto use a major version upgrade strategy..... To upgrade from beta <when\nthere was no catversion change>, just installing the new version and\nrestarting PostgreSQL is enough.\n\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, Sep 16, 2020 at 2:34 PM Jonathan S. Katz <jkatz@postgresql.org> wrote:On 9/16/20 1:08 AM, Peter Eisentraut wrote:\n> On 2020-09-15 18:10, Jonathan S. Katz wrote:\n>> To upgrade to PostgreSQL 13 RC 1 from Beta 3 or an earlier version of\n>> PostgreSQL 13, you will need to use a strategy similar to upgrading\n>> between\n>> major versions of PostgreSQL (e.g. `pg_upgrade` or `pg_dump` /\n>> `pg_restore`).\n> \n> Is this correct?  I don't see a catversion change between beta3 and rc1.\n\nWe've typically recommended doing the pg_upgrade since they may be\ncoming from a version with a lower catversion. I can change \"you will\nneed\" to \"you may need\" to be more accurate, but then that leads to the\nquestion \"who may need?\".\n\nPerhaps the safest way to say it would be:\n\n\"To upgrade to PostgreSQL 13 RC 1 from Beta 3 or an earlier version of\nPostgreSQL 13, you may need to use a strategy for upgrading between\nmajor versions of PostgreSQL (e.g. `pg_upgrade` or `pg_dump` /\n`pg_restore`). If you are unsure of the upgrade strategy to use, we\nrecommend using the major version upgrade strategy.\" \n\n(Though, this is why when typically brought up, I leave it at need, as\nit's more succinct, and those who are typically upgrading between betas\n+ rcs tend to be more in the weeds anyway ;)\n\n> Also, if correct, the word \"similar\" seems redundant or confusing here.\n\nSo if we opt to keep the above language:\n\n\"To upgrade to PostgreSQL 13 RC 1 from Beta 3 or an earlier version of\nPostgreSQL 13, you will need to use a major version upgrade strategy,\ne.g. `pg_upgrade` or `pg_dump` / `pg_restore`.\" Maybe something like:To upgrade from beta <when was the last catversion change>, you will need to use a major version upgrade strategy..... To upgrade from beta <when there was no catversion change>, just installing the new version and restarting PostgreSQL is enough.--  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Wed, 16 Sep 2020 14:47:13 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: PostgreSQL 13 RC 1 release announcement draft" }, { "msg_contents": "Magnus Hagander <magnus@hagander.net> writes:\n> On Wed, Sep 16, 2020 at 2:34 PM Jonathan S. Katz <jkatz@postgresql.org>\n> wrote:\n>> We've typically recommended doing the pg_upgrade since they may be\n>> coming from a version with a lower catversion. I can change \"you will\n>> need\" to \"you may need\" to be more accurate, but then that leads to the\n>> question \"who may need?\".\n\n> Maybe something like:\n\n> To upgrade from beta <when was the last catversion change>, you will need\n> to use a major version upgrade strategy..... To upgrade from beta <when\n> there was no catversion change>, just installing the new version and\n> restarting PostgreSQL is enough.\n\nThe last catversion bump was between beta2 and beta3. Thus, if you\nwere using beta2 or earlier, you *will* need a pg_upgrade or whatever.\nIf you were on beta3 then it's more like a minor upgrade, just install\nthe release executables and go.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 16 Sep 2020 09:52:32 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: PostgreSQL 13 RC 1 release announcement draft" }, { "msg_contents": "On 9/16/20 9:52 AM, Tom Lane wrote:\n> Magnus Hagander <magnus@hagander.net> writes:\n>> On Wed, Sep 16, 2020 at 2:34 PM Jonathan S. Katz <jkatz@postgresql.org>\n>> wrote:\n>>> We've typically recommended doing the pg_upgrade since they may be\n>>> coming from a version with a lower catversion. I can change \"you will\n>>> need\" to \"you may need\" to be more accurate, but then that leads to the\n>>> question \"who may need?\".\n> \n>> Maybe something like:\n> \n>> To upgrade from beta <when was the last catversion change>, you will need\n>> to use a major version upgrade strategy..... To upgrade from beta <when\n>> there was no catversion change>, just installing the new version and\n>> restarting PostgreSQL is enough.\n> \n> The last catversion bump was between beta2 and beta3. Thus, if you\n> were using beta2 or earlier, you *will* need a pg_upgrade or whatever.\n> If you were on beta3 then it's more like a minor upgrade, just install\n> the release executables and go.\n\n...so this is why I typically leave the language as is. There are a\nbunch of more correct permutations for how to describe what to do that\nit's just simpler to say \"will need to use...\"\n\nAnd because it's for betas/rc, the typical profile of one adopting the\nbetas are typically either developing the software or are very\nexperienced users. For those who are kicking the tires, the message\nprovides the safest of all options.\n\nNow, if this were an update release, and if for whatever we had included\na catversion bump in the update release, I'd certainly mention that\nexplicitly.\n\nMy inclination is to leave the statement alone or use that 2nd proposal\nI listed upthread.\n\nJonathan", "msg_date": "Wed, 16 Sep 2020 10:05:43 -0400", "msg_from": "\"Jonathan S. Katz\" <jkatz@postgresql.org>", "msg_from_op": true, "msg_subject": "Re: PostgreSQL 13 RC 1 release announcement draft" }, { "msg_contents": "\"Jonathan S. Katz\" <jkatz@postgresql.org> writes:\n> My inclination is to leave the statement alone or use that 2nd proposal\n> I listed upthread.\n\nI'd go with the simplest wording. As you say, people running betas\nare probably sufficiently versed in what to do that they don't need\nthe release announcement to tell them.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 16 Sep 2020 10:21:56 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: PostgreSQL 13 RC 1 release announcement draft" } ]
[ { "msg_contents": "Hi,\n\n> During fully-cached SELECT-only test using pgbench, Postgres v13Beta1\n> shows ~45% performance drop [2] at high DB connection counts (when\n> compared with v12.3)\n\nIt'd be great if we could also give credit to \"Sean Massey\" for this find.\n\nThis study on performance regression was done after his (internal) triaging\nthat the v13 regression disappeared before this commit. \n\nI regret the omission in the original post.\n-\nthanks\nrobins\n\n\n", "msg_date": "Wed, 16 Sep 2020 10:55:04 +0000", "msg_from": "\"Tharakan, Robins\" <tharar@amazon.com>", "msg_from_op": true, "msg_subject": "RE: track_planning causing performance regression" }, { "msg_contents": "Hi,\n\nAttached is a patch that adds Sean's name to the Release 13 Docs.\n\n> It'd be great if we could also give credit to \"Sean Massey\" for this\n> find.\n> \n> This study on performance regression was done after his (internal)\n> triaging that the v13 regression disappeared before this commit.\n> \n> I regret the omission in the original post.\n\nOnce again regret mentioning this earlier, but hope this is in time before GA :(\n\n-\nthanks\nrobins", "msg_date": "Thu, 17 Sep 2020 23:38:16 +0000", "msg_from": "\"Tharakan, Robins\" <tharar@amazon.com>", "msg_from_op": true, "msg_subject": "RE: track_planning causing performance regression" }, { "msg_contents": "\"Tharakan, Robins\" <tharar@amazon.com> writes:\n>> During fully-cached SELECT-only test using pgbench, Postgres v13Beta1\n>> shows ~45% performance drop [2] at high DB connection counts (when\n>> compared with v12.3)\n\n> It'd be great if we could also give credit to \"Sean Massey\" for this find.\n\nI poked through my Postgres inbox, and couldn't find any previous\nmail from or mentioning a Sean Massey.\n\nWhile there's not much of a formal policy around this, we usually limit\nourselves to crediting people who have directly interacted with the PG\ncommunity. I'm aware that there's more than a few cases where someone\ntalks to the community on behalf of a company-internal team ... but\nsince we have little visibility into such situations, whoever's doing\nthe talking gets all the credit.\n\nGiven that background, it seems like crediting Sean here would be\nslightly unfair special treatment. I'd encourage him to join the\nmailing lists and be part of the community directly --- then we'll\ndefinitely know what he's contributed.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 17 Sep 2020 23:43:09 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: track_planning causing performance regression" } ]
[ { "msg_contents": "The current Bloom index implementation only supports = operator, but states\nin the documentation that it could be extended to handle array intersection\nor union queries in future. As the original authors are hanging out in this\nlist, I would like to discuss what such implementation might be.\n\nI just started the investigation and most of what I am writing here is\nlikely faulty. What I currently ponder is if it were sufficient to OR the\nhashed array values together and store in one go to the index, or if each\narray value would need to be stored separately. The index insertion looks\nsomewhat costly, and it does not feel right to repeat that work for each\narray element. The same would apply to the set membership queries - single\nor many. If I am not totally mistaken, this depends on the number of\ndifferent hashing functions used, as each function would yield different\nvalues. However, if I understood the operator class for the current bloom\nindex, we only give one hash function?\n\nMy own C skills are getting a bit rusty and I am new to pg codebase, but\nI'll take that as a positive challenge. Any help in the algorithm and/or\nimplementation would be appreciated (even a small paid contribution would\nnot be out of question).\n\nAs to the problem I aim to solve, our small startup recently bumped into a\nperformance problem where I believe bloom index might help. We use arrays\nextensively in our activity log, which stores a reference to pretty much\nevery record that changed during an activity. It is a somewhat heavy\nstructure, and while we index it using GIN indexes and partition by\ntimestamp, it already becomes slow to query with >10M rows. Surprisingly\nthe GIN index works slower than a full table scan to the partition within\nthe query time range. The table structure could be changed (e.g. unroll the\narrays, resulting in 10-20x the rows), but I'd like to exercise if the\nproblem could be solved with proper indexes, first.\n\nI believe bloom index, supported by array intersection queries would be an\nideal solution - the hashed values would be neatly packed into one hash\n(with the obvious need to do re-checks, esp. when the arrays have a lot of\nvalues).\n\nThanks in advance,\nLauri\n\nThe current Bloom index implementation only supports = operator, but states in the documentation that it could be extended to handle array intersection or union queries in future. As the original authors are hanging out in this list, I would like to discuss what such implementation might be.I just started the investigation and most of what I am writing here is likely faulty. What I currently ponder is if it were sufficient to OR the hashed array values together and store in one go to the index, or if each array value would need to be stored separately. The index insertion looks somewhat costly, and it does not feel right to repeat that work for each array element. The same would apply to the set membership queries - single or many. If I am not totally mistaken, this depends on the number of different hashing functions used, as each function would yield different values. However, if I understood the operator class for the current bloom index, we only give one hash function?My own C skills are getting a bit rusty and I am new to pg codebase, but I'll take that as a positive challenge. Any help in the algorithm and/or implementation would be appreciated (even a small paid contribution would not be out of question).As to the problem I aim to solve, our small startup recently bumped into a performance problem where I believe bloom index might help. We use arrays extensively in our activity log, which stores a reference to pretty much every record that changed during an activity. It is a somewhat heavy structure, and while we index it using GIN indexes and partition by timestamp, it already becomes slow to query with >10M rows. Surprisingly the GIN index works slower than a full table scan to the partition within the query time range. The table structure could be changed (e.g. unroll the arrays, resulting in 10-20x the rows), but I'd like to exercise if the problem could be solved with proper indexes, first.I believe bloom index, supported by array intersection queries would be an ideal solution - the hashed values would be neatly packed into one hash (with the obvious need to do re-checks, esp. when the arrays have a lot of values).Thanks in advance,Lauri", "msg_date": "Wed, 16 Sep 2020 14:34:26 +0300", "msg_from": "Lauri Svan <lauri.svan@rescomms.com>", "msg_from_op": true, "msg_subject": "Extending array intersection ops to bloom indexes" } ]
[ { "msg_contents": "Hello,\n\nToday I bumped into an issue with pg_rewind which is not 100% clear\nwhere should be better fixed.\n\nThe first call of pg_rewind failed with the following message:\nservers diverged at WAL location A76/39E55338 on timeline 132\ncould not open file\n\"/home/postgres/pgdata/pgroot/data/pg_wal/0000008400000A760000001E\":\nNo such file or directory\n\ncould not find previous WAL record at A76/1EFFE620\nFailure, exiting\n\nIn order to avoid rebuilding the replica from scratch, we restored the\nmissing file by calling restore_command (wal-g) and repeated the call\nof pg_rewind.\n\nThe second time pg_rewind also failed, but the error looked differently:\nservers diverged at WAL location A76/39E55338 on timeline 132\nrewinding from last common checkpoint at A76/1EF254B8 on timeline 132\n\ncould not remove file\n\"/home/postgres/pgdata/pgroot/data/pg_wal/.wal-g/prefetch/running/0000008400000A7600000024\":\nNo such file or directory\nFailure, exiting\n\nThe second call left PGDATA in an inconsistent state (empty pg_control).\n\nA few words about where the pg_wal/.wal-g/prefetch/running/ is coming\nfrom: wal-g by default when fetching the WAL file is also trying to do\na prefetch of a few next WAL files. For that it forks and the child\nprocess doing prefetch while the parent process exits. In order to\navoid multiple parallel prefetches of the same file, wal-g keeps its\nstate in the pg_wal/.wal-g directory. It also keeps prefetched files\nthere.\n\nWhat in fact happened: pg_rewind is building a list of files in the\ntarget directory which don't match with the source directory and\ntherefore must be changed (copied/removed/truncated/etc). When the\nlist was built, the wal-g prefetch was still running, but when\npg_rewind tried to remove files that should not be there because they\ndon't exist in the source directory it failed with the fatal error.\n\nThe issue occurred on 10.14, but I believe very similar might happen\nwith postgres 13 when pg_rewind is called with --restore-target-wal\noption.\n\nOne might argue that the issue should be fixed in wal-g (it should not\nmess up with pg_wal), and I personally 99% agree with that, but so far\nthis behavior was safe, because postgres itself never looks inside\nunexpected directories in pg_wal. Also from the usability perspective\nit is very convenient to keep prefetched files in the pg_wal/.wal-g,\nbecause it guarantees 100% that they will be located on the same\nfilesystem as pg_wal and therefore the next time when the\nrestore_command is called it is enough just to rename the file.\n\nThat made me think about how it could be improved in the pg_rewind.\nThe thing is, that we want to have a specific file to be removed, and\nit is already not there. Should it be a fatal error?\ntraverse_datadir()/recurse_dir() already ignoring all failed lstat()\ncalls with errno == ENOENT.\n\nBasically I have to options:\n1. Remove modify remove_target_file(const char *path, bool missing_ok)\nfunction and remove the missing_ok option, that would be consistent\nwith recurse_dir()\n2. Change the logic of remove_target_file(), so it doesn't exit with\nthe fatal error if the file is missing, but shows only a warning.\n\nIn addition to the aforementioned options the remove_target_dir() also\nshould be improved, i.e. it should check errno and behave similarly to\nthe remove_target_file() if the errno == ENOENT\n\nWhat do you think?\n\nRegards,\n--\nAlexander Kukushkin\n\n\n", "msg_date": "Wed, 16 Sep 2020 14:55:08 +0200", "msg_from": "Alexander Kukushkin <cyberdemn@gmail.com>", "msg_from_op": true, "msg_subject": "Concurrency issue in pg_rewind" }, { "msg_contents": "On Wed, Sep 16, 2020 at 2:55 PM Alexander Kukushkin <cyberdemn@gmail.com>\nwrote:\n\n>\n> The second time pg_rewind also failed, but the error looked differently:\n> servers diverged at WAL location A76/39E55338 on timeline 132\n> rewinding from last common checkpoint at A76/1EF254B8 on timeline 132\n>\n> could not remove file\n>\n> \"/home/postgres/pgdata/pgroot/data/pg_wal/.wal-g/prefetch/running/0000008400000A7600000024\":\n>\n\nOuch. I think pg_rewind shouldn't try to remove any random files in pg_wal\nthat it doesn't know about.\nWhat if the administrator made a backup of some WAL segments there?\n\n--\nAlex\n\nOn Wed, Sep 16, 2020 at 2:55 PM Alexander Kukushkin <cyberdemn@gmail.com> wrote:\nThe second time pg_rewind also failed, but the error looked differently:\nservers diverged at WAL location A76/39E55338 on timeline 132\nrewinding from last common checkpoint at A76/1EF254B8 on timeline 132\n\ncould not remove file\n\"/home/postgres/pgdata/pgroot/data/pg_wal/.wal-g/prefetch/running/0000008400000A7600000024\":Ouch.  I think pg_rewind shouldn't try to remove any random files in pg_wal that it doesn't know about.What if the administrator made a backup of some WAL segments there?--Alex", "msg_date": "Thu, 17 Sep 2020 10:20:16 +0200", "msg_from": "Oleksandr Shulgin <oleksandr.shulgin@zalando.de>", "msg_from_op": false, "msg_subject": "Re: Concurrency issue in pg_rewind" }, { "msg_contents": "On 2020-09-16 15:55, Alexander Kukushkin wrote:\n> Hello,\n> \n> Today I bumped into an issue with pg_rewind which is not 100% clear\n> where should be better fixed.\n> \n> The first call of pg_rewind failed with the following message:\n> servers diverged at WAL location A76/39E55338 on timeline 132\n> could not open file\n> \"/home/postgres/pgdata/pgroot/data/pg_wal/0000008400000A760000001E\":\n> No such file or directory\n> \n> could not find previous WAL record at A76/1EFFE620\n> Failure, exiting\n> \n> In order to avoid rebuilding the replica from scratch, we restored the\n> missing file by calling restore_command (wal-g) and repeated the call\n> of pg_rewind.\n> \n> The second time pg_rewind also failed, but the error looked \n> differently:\n> servers diverged at WAL location A76/39E55338 on timeline 132\n> rewinding from last common checkpoint at A76/1EF254B8 on timeline 132\n> \n> could not remove file\n> \"/home/postgres/pgdata/pgroot/data/pg_wal/.wal-g/prefetch/running/0000008400000A7600000024\":\n> No such file or directory\n> Failure, exiting\n> \n> The second call left PGDATA in an inconsistent state (empty \n> pg_control).\n> \n> A few words about where the pg_wal/.wal-g/prefetch/running/ is coming\n> from: wal-g by default when fetching the WAL file is also trying to do\n> a prefetch of a few next WAL files. For that it forks and the child\n> process doing prefetch while the parent process exits. In order to\n> avoid multiple parallel prefetches of the same file, wal-g keeps its\n> state in the pg_wal/.wal-g directory. It also keeps prefetched files\n> there.\n> \n\nHm, I cannot understand why wal-g (or any other tool) is trying to run \npg_rewind, while WAL copying (and prefetch) is still in progress? Why do \nnot just wait until it is finished?\n\nIt is also not clear for me why it does not put prefetched WAL files \ndirectly into the pg_wal?\n\n> \n> The issue occurred on 10.14, but I believe very similar might happen\n> with postgres 13 when pg_rewind is called with --restore-target-wal\n> option.\n> \n\nWith --restore-target-wal pg_rewind is trying to call restore_command on \nits own and it can happen at two stages:\n\n1) When pg_rewind is trying to find the last checkpoint preceding a \ndivergence point. In that case file map is not even yet initialized. \nThus, all fetched WAL segments at this stage will be present in the file \nmap created later.\n\n2) When it creates a data pages map. It should traverse WAL from the \nlast common checkpoint till the final shutdown point in order to find \nall modified pages on the target. At this stage pg_rewind only updates \ninfo about data segments in the file map. That way, I see a minor \nproblem that WAL segments fetched at this stage would not be deleted, \nsince they are absent in the file map.\n\nAnyway, pg_rewind does not delete neither WAL segments, not any other \nfiles in the middle of the file map creation, so I cannot imagine, how \nit can get into the same trouble on its own.\n\n> \n> That made me think about how it could be improved in the pg_rewind.\n> The thing is, that we want to have a specific file to be removed, and\n> it is already not there. Should it be a fatal error?\n> traverse_datadir()/recurse_dir() already ignoring all failed lstat()\n> calls with errno == ENOENT.\n> \n\nrecurse_dir() is also called on the source, which should be running when \n--source-server is used, so it can remove files. There is actually a \nTODO there:\n\n/*\n * File doesn't exist anymore. This is ok, if the new master\n * is running and the file was just removed. If it was a data\n * file, there should be a WAL record of the removal. If it\n * was something else, it couldn't have been anyway.\n *\n * TODO: But complain if we're processing the target dir!\n */\n\n> \n> Basically I have to options:\n> 1. Remove modify remove_target_file(const char *path, bool missing_ok)\n> function and remove the missing_ok option, that would be consistent\n> with recurse_dir()\n> 2. Change the logic of remove_target_file(), so it doesn't exit with\n> the fatal error if the file is missing, but shows only a warning.\n> \n> In addition to the aforementioned options the remove_target_dir() also\n> should be improved, i.e. it should check errno and behave similarly to\n> the remove_target_file() if the errno == ENOENT\n> \n> What do you think?\n> \n\nAlthough keeping arbitrary files inside PGDATA does not look like a good \nidea for me, I do not see anything criminal in skipping non-existing \nfile, when executing a file map by pg_rewind.\n\n\nRegards\n-- \nAlexey Kondratov\n\nPostgres Professional https://www.postgrespro.com\nRussian Postgres Company\n\n\n", "msg_date": "Thu, 17 Sep 2020 15:04:12 +0300", "msg_from": "Alexey Kondratov <a.kondratov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Concurrency issue in pg_rewind" }, { "msg_contents": "On Thu, 17 Sep 2020 at 14:04, Alexey Kondratov\n<a.kondratov@postgrespro.ru> wrote:\n>\n> Hm, I cannot understand why wal-g (or any other tool) is trying to run\n> pg_rewind, while WAL copying (and prefetch) is still in progress? Why do\n> not just wait until it is finished?\n\nwal-g doesn't try to call pg_rewind.\nFirst, we called wal-g, it fetched the file we requested and exited.\nBut, before exiting, wal-g forks, and the child process does prefetch\nof a few next WALs.\nWe don't really know when the child process exits and can't wait for it.\n\n>\n> It is also not clear for me why it does not put prefetched WAL files\n> directly into the pg_wal?\n\nBecause this is how postgres works. It doesn't matter whether the\nspecific WAL segment is there, postgres will call the restore_command\nanyway.\nThe restore command also doesn't know if the file in pg_wal is OK,\ntherefore keeping the prefetched file in some other place and moving\nit seems to be a good approach.\n\n> With --restore-target-wal pg_rewind is trying to call restore_command on\n> its own and it can happen at two stages:\n>\n> 1) When pg_rewind is trying to find the last checkpoint preceding a\n> divergence point. In that case file map is not even yet initialized.\n> Thus, all fetched WAL segments at this stage will be present in the file\n> map created later.\n\nNope, it will fetch files you requested, and in addition to that it\nwill leave a child process running in the background which is doing\nthe prefetch (manipulating with pg_wal/.wal-g/...)\n\n>\n> 2) When it creates a data pages map. It should traverse WAL from the\n> last common checkpoint till the final shutdown point in order to find\n> all modified pages on the target. At this stage pg_rewind only updates\n> info about data segments in the file map. That way, I see a minor\n> problem that WAL segments fetched at this stage would not be deleted,\n> since they are absent in the file map.\n>\n> Anyway, pg_rewind does not delete neither WAL segments, not any other\n> files in the middle of the file map creation, so I cannot imagine, how\n> it can get into the same trouble on its own.\n\nWhen pg_rewind was creating the map, some temporary files where there,\nbecause the forked child process of wal-g was still running.\nWhen the wal-g child process exits, it removes some of these files.\nSpecifically, it was trying to prefetch 0000008400000A7600000024 into\nthe pg_wal/.wal-g/prefetch/running/0000008400000A7600000024, but\napparently the file wasn't available on S3 and prefetch failed,\ntherefore the empty file was removed.\n\n\n> Although keeping arbitrary files inside PGDATA does not look like a good\n> idea for me, I do not see anything criminal in skipping non-existing\n> file, when executing a file map by pg_rewind.\n\nGood, I will prepare a patch then.\n\nRegards,\n--\nAlexander Kukushkin\n\n\n", "msg_date": "Thu, 17 Sep 2020 14:27:13 +0200", "msg_from": "Alexander Kukushkin <cyberdemn@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Concurrency issue in pg_rewind" }, { "msg_contents": "On 2020-09-17 15:27, Alexander Kukushkin wrote:\n> On Thu, 17 Sep 2020 at 14:04, Alexey Kondratov\n> <a.kondratov@postgrespro.ru> wrote:\n> \n>> With --restore-target-wal pg_rewind is trying to call restore_command \n>> on\n>> its own and it can happen at two stages:\n>> \n>> 1) When pg_rewind is trying to find the last checkpoint preceding a\n>> divergence point. In that case file map is not even yet initialized.\n>> Thus, all fetched WAL segments at this stage will be present in the \n>> file\n>> map created later.\n> \n> Nope, it will fetch files you requested, and in addition to that it\n> will leave a child process running in the background which is doing\n> the prefetch (manipulating with pg_wal/.wal-g/...)\n> \n>> \n>> 2) When it creates a data pages map. It should traverse WAL from the\n>> last common checkpoint till the final shutdown point in order to find\n>> all modified pages on the target. At this stage pg_rewind only updates\n>> info about data segments in the file map. That way, I see a minor\n>> problem that WAL segments fetched at this stage would not be deleted,\n>> since they are absent in the file map.\n>> \n>> Anyway, pg_rewind does not delete neither WAL segments, not any other\n>> files in the middle of the file map creation, so I cannot imagine, how\n>> it can get into the same trouble on its own.\n> \n> When pg_rewind was creating the map, some temporary files where there,\n> because the forked child process of wal-g was still running.\n> When the wal-g child process exits, it removes some of these files.\n> Specifically, it was trying to prefetch 0000008400000A7600000024 into\n> the pg_wal/.wal-g/prefetch/running/0000008400000A7600000024, but\n> apparently the file wasn't available on S3 and prefetch failed,\n> therefore the empty file was removed.\n> \n\nI do understand how you got into this problem with wal-g. This part of \nmy answer was about bare postgres and pg_rewind. And my point was that \nfrom my perspective pg_rewind with --restore-target-wal cannot get into \nthe same trouble on its own, without 'help' of some side tools like \nwal-g.\n\n\nRegards\n-- \nAlexey Kondratov\n\nPostgres Professional https://www.postgrespro.com\nRussian Postgres Company\n\n\n", "msg_date": "Thu, 17 Sep 2020 16:05:28 +0300", "msg_from": "Alexey Kondratov <a.kondratov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Concurrency issue in pg_rewind" }, { "msg_contents": "On Thu, Sep 17, 2020 at 10:20:16AM +0200, Oleksandr Shulgin wrote:\n> Ouch. I think pg_rewind shouldn't try to remove any random files in pg_wal\n> that it doesn't know about.\n> What if the administrator made a backup of some WAL segments there?\n\nIMO, this would be a rather bad strategy anyway, so just don't do\nthat, because that could also mean that this is on the same partition\nas pg_wal/ which would crash the server if the partition has the idea\nto get full even if max_wal_size is set correctly. If you think about\nthat, this is rather similar to putting tablespaces in your root data\nfolder: it may look fancy, but you just make the task of the backend\nmore complicated. Note that this practice is not wise when Postgres\ndecides to apply actions that loop across the entire tree, just to\nname two of them: the full fsync of PGDATA at the beginning of crash\nrecovery or just a base backup.\n--\nMichael", "msg_date": "Fri, 18 Sep 2020 15:10:11 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Concurrency issue in pg_rewind" }, { "msg_contents": "\n\n> 18 сент. 2020 г., в 11:10, Michael Paquier <michael@paquier.xyz> написал(а):\n> \n> On Thu, Sep 17, 2020 at 10:20:16AM +0200, Oleksandr Shulgin wrote:\n>> Ouch. I think pg_rewind shouldn't try to remove any random files in pg_wal\n>> that it doesn't know about.\n>> What if the administrator made a backup of some WAL segments there?\n> \n> IMO, this would be a rather bad strategy anyway, so just don't do\n> that, because that could also mean that this is on the same partition\n> as pg_wal/ \n\nThis is whole point of having prefetch. restore_command just links file from the same partition.\nIn WAL-G you strictly control number of cached WALs, so if you configured max_wal_size - you can configure WALG_DOWNLOAD_CONCURRENCY too.\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Fri, 18 Sep 2020 11:31:26 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Concurrency issue in pg_rewind" }, { "msg_contents": "On Fri, Sep 18, 2020 at 11:31:26AM +0500, Andrey M. Borodin wrote:\n> This is whole point of having prefetch. restore_command just links\n> file from the same partition.\n\nIf this stuff is willing to do so, you may have your reasons, but even\nif you wish to locate both pg_wal/ and the prefetch path in the same\npartition, I don't get why it is necessary to have the prefetch path\nincluded directly in pg_wal? You could just use different paths for\nboth. Say, with a base partition at /my/path/, you can just have\n/my/path/pg_wal/ that the Postgres backend links to, and\n/my/path/wal-g/prefetch/ for the secondary path.\n--\nMichael", "msg_date": "Fri, 18 Sep 2020 15:59:45 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Concurrency issue in pg_rewind" }, { "msg_contents": "Hi,\n\nOn Fri, 18 Sep 2020 at 08:59, Michael Paquier <michael@paquier.xyz> wrote:\n\n> If this stuff is willing to do so, you may have your reasons, but even\n> if you wish to locate both pg_wal/ and the prefetch path in the same\n> partition, I don't get why it is necessary to have the prefetch path\n> included directly in pg_wal? You could just use different paths for\n> both. Say, with a base partition at /my/path/, you can just have\n> /my/path/pg_wal/ that the Postgres backend links to, and\n> /my/path/wal-g/prefetch/ for the secondary path.\n\nWell, I agree and disagree at the same time.\nYes, it would be nice not to write anything unexpected to PGDATA and\npg_wal, but this is also a usability issue.\nCreating a separate directory and configuring wal-e/wal-g to use it\n(now it is not even possible to configure it), requires some effort\nfrom the administrator, while using something inside pg_wal just\nworks.\n\nAt the same time, pg_rewind due to such \"fatal\" error leaves PGDATA in\nan inconsistent state with empty pg_control file, this is totally bad\nand easily fixable. We want the specific file to be absent and it is\nalready absent, why should it be a fatal error and not warning?\n\nRegards,\n--\nAlexander Kukushkin\n\n\n", "msg_date": "Fri, 18 Sep 2020 09:17:23 +0200", "msg_from": "Alexander Kukushkin <cyberdemn@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Concurrency issue in pg_rewind" }, { "msg_contents": "On Fri, Sep 18, 2020 at 8:10 AM Michael Paquier <michael@paquier.xyz> wrote:\n\n> On Thu, Sep 17, 2020 at 10:20:16AM +0200, Oleksandr Shulgin wrote:\n> > Ouch. I think pg_rewind shouldn't try to remove any random files in\n> pg_wal\n> > that it doesn't know about.\n> > What if the administrator made a backup of some WAL segments there?\n>\n> IMO, this would be a rather bad strategy anyway, so just don't do\n> that, because that could also mean that this is on the same partition\n> as pg_wal/ which would crash the server if the partition has the idea\n> to get full even if max_wal_size is set correctly.\n\n\nTo clarify my point, I don't mean to backup WAL segments in the background\nwhen the server is running, but precisely when the server is down and you\nneed to intervene, such as running pg_rewind. You might want to \"stash\"\nsome of the latest segments in case you need to start over (name it\npg_wal/0000008400000A760000001E.backup, or\npg_wal/backup/0000008400000A760000001E). It is surprising that pg_rewind\nmight want to decide to remove those.\n\n--\nAlex\n\nOn Fri, Sep 18, 2020 at 8:10 AM Michael Paquier <michael@paquier.xyz> wrote:On Thu, Sep 17, 2020 at 10:20:16AM +0200, Oleksandr Shulgin wrote:\n> Ouch.  I think pg_rewind shouldn't try to remove any random files in pg_wal\n> that it doesn't know about.\n> What if the administrator made a backup of some WAL segments there?\n\nIMO, this would be a rather bad strategy anyway, so just don't do\nthat, because that could also mean that this is on the same partition\nas pg_wal/ which would crash the server if the partition has the idea\nto get full even if max_wal_size is set correctly.To clarify my point, I don't mean to backup WAL segments in the background when the server is running, but precisely when the server is down and you need to intervene, such as running pg_rewind.  You might want to \"stash\" some of the latest segments in case you need to start over (name it pg_wal/0000008400000A760000001E.backup, or pg_wal/backup/0000008400000A760000001E).  It is surprising that pg_rewind might want to decide to remove those.--Alex", "msg_date": "Fri, 18 Sep 2020 10:50:19 +0200", "msg_from": "Oleksandr Shulgin <oleksandr.shulgin@zalando.de>", "msg_from_op": false, "msg_subject": "Re: Concurrency issue in pg_rewind" }, { "msg_contents": "\n\n> 18 сент. 2020 г., в 11:59, Michael Paquier <michael@paquier.xyz> написал(а):\n> \n> On Fri, Sep 18, 2020 at 11:31:26AM +0500, Andrey M. Borodin wrote:\n>> This is whole point of having prefetch. restore_command just links\n>> file from the same partition.\n> \n> If this stuff is willing to do so, you may have your reasons, but even\n> if you wish to locate both pg_wal/ and the prefetch path in the same\n> partition, I don't get why it is necessary to have the prefetch path\n> included directly in pg_wal? You could just use different paths for\n> both. Say, with a base partition at /my/path/, you can just have\n> /my/path/pg_wal/ that the Postgres backend links to, and\n> /my/path/wal-g/prefetch/ for the secondary path.\n\nThis complexity doesn't seem necessary to me. What we gain? Prefetched WAL is WAL per se. Makes sense to keep it in pg_wal tree by default.\n\nI will implement possibility to move cache out of pg_wal (similar functionality is implemented in pgBackRest). But it seems useless to me: user can configure WAL prefetch to be less performant, without any benefits.\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Fri, 18 Sep 2020 17:33:26 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Concurrency issue in pg_rewind" }, { "msg_contents": "On 18/09/2020 10:17, Alexander Kukushkin wrote:\n> At the same time, pg_rewind due to such \"fatal\" error leaves PGDATA in\n> an inconsistent state with empty pg_control file, this is totally bad\n> and easily fixable. We want the specific file to be absent and it is\n> already absent, why should it be a fatal error and not warning?\n\nWhenever pg_rewind runs into something unexpected, it fails loudly, so \nthat the administrator can re-initialize from a base backup. That's the \ngeneral rule. If a file goes missing while pg_rewind is running, that is \nunexpected. It could be a sign that the server was started concurrently, \nor another pg_rewind was started against it, for example.\n\nI feel that we could make an exception of some sort here, but I'm not \nsure what exactly. I don't feel comfortable just downgrading the \nunexpected ENOENT on unlink() to warning in all cases. Besides, scary \nwarnings that you routinely ignore is not good either.\n\nI have a hard time coming up with a general rule and justification \nthat's not just \"do X because WAL-G does Y\". pg_rewind failing because \nWAL-G removed a file unexpectedly is one problem, but another is that \nthe restore_command might get confused if a pg_rewind removes a file \nthat restore_command needs. This is hard when restore_command does \nthings in the background, and there's no communication between the \nbackground process and pg_rewind.\n\nThe general principle is that pg_rewind is equivalent to overwriting the \ntarget with the source, only faster. Perhaps pg_wal should be an \nexception, and pg_rewind should leave alone any files under pg_wal that \nit doesn't recognize.\n\n- Heikki\n\n\n", "msg_date": "Tue, 29 Sep 2020 09:49:31 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Concurrency issue in pg_rewind" }, { "msg_contents": "Greetings,\n\n* Heikki Linnakangas (hlinnaka@iki.fi) wrote:\n> On 18/09/2020 10:17, Alexander Kukushkin wrote:\n> >At the same time, pg_rewind due to such \"fatal\" error leaves PGDATA in\n> >an inconsistent state with empty pg_control file, this is totally bad\n> >and easily fixable. We want the specific file to be absent and it is\n> >already absent, why should it be a fatal error and not warning?\n> \n> Whenever pg_rewind runs into something unexpected, it fails loudly, so that\n> the administrator can re-initialize from a base backup. That's the general\n> rule. If a file goes missing while pg_rewind is running, that is unexpected.\n> It could be a sign that the server was started concurrently, or another\n> pg_rewind was started against it, for example.\n\nAgreed.\n\n> I feel that we could make an exception of some sort here, but I'm not sure\n> what exactly. I don't feel comfortable just downgrading the unexpected\n> ENOENT on unlink() to warning in all cases. Besides, scary warnings that you\n> routinely ignore is not good either.\n\nI also dislike the idea of downgrading this.\n\n> I have a hard time coming up with a general rule and justification that's\n> not just \"do X because WAL-G does Y\". pg_rewind failing because WAL-G\n> removed a file unexpectedly is one problem, but another is that the\n> restore_command might get confused if a pg_rewind removes a file that\n> restore_command needs. This is hard when restore_command does things in the\n> background, and there's no communication between the background process and\n> pg_rewind.\n\nI would also point out that wal-g isn't the only backup/restore tool\nthat does pre-fetching: so does pgbackrest, but we pre-fetch into an\nindependent spool directory, because these tools really should *not* be\nmodifying the PGDATA directory during restore_command.\n\nI'm really disinclined to make concessions for external tools to start\nwriting into directories that they shouldn't be- and this goes for\nremoving .ready files too, imv. Yes, you can do such things and maybe\nthings will work, but if you run into issues with that, that's on you\nfor making changes to the PGDATA directory, not on PG to try and guess\nat what you, or any other external tool, did and magically work around\nit or keep it working.\n\nThanks,\n\nStephen", "msg_date": "Wed, 7 Oct 2020 15:13:12 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Concurrency issue in pg_rewind" }, { "msg_contents": "Greetings,\n\n* Andrey M. Borodin (x4mmm@yandex-team.ru) wrote:\n> > 18 сент. 2020 г., в 11:59, Michael Paquier <michael@paquier.xyz> написал(а):\n> > On Fri, Sep 18, 2020 at 11:31:26AM +0500, Andrey M. Borodin wrote:\n> >> This is whole point of having prefetch. restore_command just links\n> >> file from the same partition.\n> > \n> > If this stuff is willing to do so, you may have your reasons, but even\n> > if you wish to locate both pg_wal/ and the prefetch path in the same\n> > partition, I don't get why it is necessary to have the prefetch path\n> > included directly in pg_wal? You could just use different paths for\n> > both. Say, with a base partition at /my/path/, you can just have\n> > /my/path/pg_wal/ that the Postgres backend links to, and\n> > /my/path/wal-g/prefetch/ for the secondary path.\n> \n> This complexity doesn't seem necessary to me. What we gain? Prefetched WAL is WAL per se. Makes sense to keep it in pg_wal tree by default.\n> \n> I will implement possibility to move cache out of pg_wal (similar functionality is implemented in pgBackRest). But it seems useless to me: user can configure WAL prefetch to be less performant, without any benefits.\n\nIn this case there's certainly one very clear benefit: pg_rewind will be\nmore robust at detecting serious issues and complaining loudly,\nhopefully avoiding having users end up with corrupted clusters. That's\ncertainly not nothing, from my perspective.\n\nThanks,\n\nStephen", "msg_date": "Wed, 7 Oct 2020 15:14:30 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Concurrency issue in pg_rewind" } ]
[ { "msg_contents": "I'm trying to develop a plpgsql function that would extract mapbox vector\ntiles from a postgresql/post gis database. The database has multiple\ngeospatial tables, so I want the function to be able to take a table name\nas a parameter.\n\nI've gotten the function to work using hard coded table names. Discussion\non functions with table name as a parameter say I need to use EXECUTE\n<https://www.postgresql.org/message-id/20011210134736.D70079-100000%40megazone23.bigpanda.com>.\nHowever, when I try and use EXECUTE in the mvtgeom AS section of the script\nI get a syntax error on EXECUTE:\n\nCREATE OR REPLACE\nFUNCTION public.region3_sim_storms_pg(z integer, x integer, y integer,\nstormtable text)\nRETURNS bytea\nAS $$\nDECLARE\n result bytea;\nBEGIN\n WITH\n bounds AS (\n SELECT ST_TileEnvelope(z, x, y) AS geom\n ),\n mvtgeom AS (\n EXECUTE format(\n 'SELECT ST_AsMVTGeom(ST_Transform(G.geom, 3857), bounds.geom, 4096,\n256, true) AS geom, node, bathymetry\n FROM %s AS G, bounds\n WHERE ST_Intersects(G.geom, ST_Transform(bounds.geom, 4326))',\nquote_ident(stormtable)\n )\n )\n SELECT ST_AsMVT(mvtgeom, 'public.region3_sim_storms_pg')\n INTO result FROM mvtgeom;\n RETURN result;\nEND\n$$\nLANGUAGE 'plpgsql'\nSTABLE\nPARALLEL SAFE;\n\nCOMMENT ON FUNCTION public.region3_sim_storms_pg IS 'Given a tile address,\nstorm name query database.';\n\nPast discussion on this topic says this error occurs because the function\nis not being recognized as a plpgsql function\n<https://stackoverflow.com/questions/6861374/postgresql-syntax-error-when-using-execute-in-function>,\nbut I have LANGUAGE 'plpgsql' specified. The only thing I can think of is\nthat things are reverted back to SQL in the \"mvtgeom AS (\" portion of the\nscript. Is there a way to use EXECUTE in the \"mvtgeom AS (\" portion of the\nscript?\n\nThanks\nJim\n\nI'm trying to develop a plpgsql function that would extract mapbox vector tiles from a postgresql/post gis database. The database has multiple geospatial tables, so I want the function to be able to take a table name as a parameter.I've gotten the function to work using hard coded table names. Discussion on functions with table name as a parameter say I need to use EXECUTE. However, when I try and use EXECUTE in the mvtgeom AS section of the script I get a syntax error on EXECUTE: CREATE OR REPLACEFUNCTION public.region3_sim_storms_pg(z integer, x integer, y integer, stormtable text)RETURNS byteaAS $$DECLARE  result bytea;BEGIN  WITH  bounds AS (    SELECT ST_TileEnvelope(z, x, y) AS geom   ),  mvtgeom AS (     EXECUTE format(       'SELECT ST_AsMVTGeom(ST_Transform(G.geom, 3857), bounds.geom, 4096, 256, true) AS geom, node, bathymetry        FROM %s AS G, bounds         WHERE ST_Intersects(G.geom, ST_Transform(bounds.geom, 4326))', quote_ident(stormtable)     )    )  SELECT ST_AsMVT(mvtgeom, 'public.region3_sim_storms_pg')  INTO result FROM mvtgeom;  RETURN result;END$$LANGUAGE 'plpgsql'STABLEPARALLEL SAFE;COMMENT ON FUNCTION public.region3_sim_storms_pg IS 'Given a tile address, storm name query database.';Past discussion on this topic says this error occurs because the function is not being recognized as a plpgsql function, but I have LANGUAGE 'plpgsql' specified. The only thing I can think of is that things are reverted back to SQL in the \"mvtgeom AS (\" portion of the script. Is there a way to use EXECUTE in the \"mvtgeom AS (\" portion of the script?ThanksJim", "msg_date": "Wed, 16 Sep 2020 10:18:58 -0400", "msg_from": "James McManus <jmpmcmanus@gmail.com>", "msg_from_op": true, "msg_subject": "ST_AsMVTGeom AND table name as parameter in pl/psql" }, { "msg_contents": "James McManus <jmpmcmanus@gmail.com> writes:\n> However, when I try and use EXECUTE in the mvtgeom AS section of the script\n> I get a syntax error on EXECUTE:\n\nYou need to convert the *entire* query into a string and apply EXECUTE\nto that. You can't use EXECUTE as a part of a query.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 16 Sep 2020 10:26:05 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: ST_AsMVTGeom AND table name as parameter in pl/psql" } ]
[ { "msg_contents": "Hello.\n\nWhile running pgbench, I found tps excluding connection somewhat\nstrange. To emphasize the behavior, I inserted some sleep at the end\nof doConnect() and ran pgbench with several times.\n\n$ pgbench -T 5 -j 1 -c 4 (with 1s sleep in doConnect())\n> number of transactions actually processed: 409\n! latency average = 48.980 ms\n> tps = 81.665671 (including connections establishing)\n> tps = 102.323285 (excluding connections establishing)\n\n$ pgbench -T 5 -j 4 -c 4 (with 1s sleep in doConnect())\n> number of transactions actually processed: 1628\n! latency average = 12.303 ms\n> tps = 325.123448 (including connections establishing)\n> tps = 422.671015 (excluding connections establishing)\n\nWhy the latencies are so different? If I tell pgbench to measure the\nlatencies, it is about 8-9ms in both cases.\n\n$ pgbench -T 5 -j 1 -c 4 -L100 (with 1s sleep in doConnect())\n> number of transactions actually processed: 419\n> number of transactions above the 100.0 ms latency limit: 0/419 (0.000 %)\n! latency average = 8.984 ms\n> latency stddev = 3.259 ms\n> tps = 83.633694 (including connections establishing)\n> tps = 104.909130 (excluding connections establishing)\n\n$ pgbench -T 5 -j 4 -c 4 -L100 (with 1s sleep in doConnect())\n> number of transactions actually processed: 2047\n> number of transactions above the 100.0 ms latency limit: 0/2047 (0.000 %)\n! latency average = 7.807 ms\n> latency stddev = 2.916 ms\n> tps = 408.677024 (including connections establishing)\n> tps = 511.837509 (excluding connections establishing)\n\nThat's reasonable. So the latency estimation is apparently a kind of\nbogus. It seems to me that the calculation is wrong to use\ntime_include. I think it should use time_exclude instead.\n\n$ pgbench -T 5 -j 1 -c 4 (with 1s sleep in doConnect())\n> number of transactions actually processed: 407\n! latency average = 11.674 ms\n> tps = 81.262992 (including connections establishing)\n> tps = 101.724507 (excluding connections establishing)\n> \n\n$ pgbench -T 5 -j 4 -c 4 (with 1s sleep in doConnect())\n> number of transactions actually processed: 1718\n! latency average = 11.674 ms\n> tps = 342.652333 (including connections establishing)\n> tps = 428.850338 (excluding connections establishing)\n\nLooks far better, but \"tps excluding connection establishing\" looks\nstrange. The reason seems to me threadRun() counts connection time a\nwrong way. thread->conn_time is assumed to be the sum of the time took\nby each client until it runs the first transaction. If each\nconnection took 1 second, conn_time of a thread that runs three\nclients is calculated as 3 seconds. But in reality, if each connection\ntook 1 second, all clients on the thread waits for 3 seconds before\nstarting a transaction so it should be 3s * 3(clients/thread) = 9\nseconds.\n\nWe could multiply conn_time by nstate on each thread, but the same\nhappens for -C (is_connect) mode. When a client took 1 second to\nestablish a connection, no other clients can do anything meanwhile.\nSomewhat different from the !is_connect case precisely, but basically\nthe same at the point that making a connection of a client actually\nblocks all other clients on the same thread.\n\nTherefore I changed nclients in the calculation of time_exclude to\nnthreads.\n\n$ pgbench -T 5 -j 1 -c 4 (with 1s sleep in doConnect())\n> number of transactions actually processed: 399\n> latency average = 9.402 ms\n> tps = 79.671581 (including connections establishing)\n> tps = 425.460179 (excluding connections establishing)\n\n$ pgbench -T 5 -j 4 -c 4 (with 1s sleep in doConnect())\n> number of transactions actually processed: 1903\n> latency average = 8.330 ms\n> tps = 379.944770 (including connections establishing)\n> tps = 480.211639 (excluding connections establishing)\n\nLooks fine. Also the -C cases looks sainer.\n\n(- is unpatched, + is patched)\n\n> $ pgbench -T 5 -j 1 -c 4 -C (with 100ms sleep in doConnect())\n### time_include=5.1, conn_total_time=4.9\n- number of transactions actually processed: 43\n- latency average = 469.850 ms\n- tps = 8.513360 (including connections establishing)\n- tps = 11.246110 (excluding connections establishing)\n+ number of transactions actually processed: 38\n+ latency average = 16.735 ms\n+ tps = 7.493800 (including connections establishing)\n+ tps = 239.022345 (excluding connections establishing)\n\n\n> $ pgbench -T 5 -j 4 -c 4 -C (with 100ms sleep in doConnect())\n### time_include=5.1, conn_total_time=18.3\n-number of transactions actually processed: 172\n-latency average = 117.571 ms\n-tps = 34.021873 (including connections establishing)\n-tps = 346.296591 (excluding connections establishing)\n+ number of transactions actually processed: 172\n+ latency average = 11.671 ms\n+ tps = 33.851599 (including connections establishing)\n+ tps = 342.716081 (excluding connections establishing)\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center", "msg_date": "Thu, 17 Sep 2020 17:41:54 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": true, "msg_subject": "pgbench calculates summary numbers a wrong way." }, { "msg_contents": "Mmm..\n\nAt Thu, 17 Sep 2020 17:41:54 +0900 (JST), Kyotaro Horiguchi <horikyota.ntt@gmail.com> wrote in \n> While running pgbench, I found tps excluding connection somewhat\n> strange. To emphasize the behavior, I inserted some sleep at the end\n> of doConnect() and ran pgbench with several times.\n<patch attached>\n\nSorry, I sent a wrong version of the patch, contains some spelling\nerrors. This is the right one.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center", "msg_date": "Thu, 17 Sep 2020 17:52:23 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": true, "msg_subject": "Re: pgbench calculates summary numbers a wrong way." }, { "msg_contents": "At Thu, 17 Sep 2020 17:52:23 +0900 (JST), Kyotaro Horiguchi <horikyota.ntt@gmail.com> wrote in \n> Sorry, I sent a wrong version of the patch, contains some spelling\n> errors. This is the right one.\n\nSigh.. I fixed some more wordings.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center", "msg_date": "Thu, 17 Sep 2020 17:59:45 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": true, "msg_subject": "Re: pgbench calculates summary numbers a wrong way." }, { "msg_contents": "\nHello,\n\n>> Sorry, I sent a wrong version of the patch, contains some spelling\n>> errors. This is the right one.\n>\n> Sigh.. I fixed some more wordings.\n\nI have submitted a patch which reworks how things are computed so that \nperformance figures make some/more sense, among other things.\n\nMaybe you could have a look at it and tell whether it is an improvement \nwrt your issue?\n\nhttps://commitfest.postgresql.org/29/2557/\n\n-- \nFabien.\n\n\n", "msg_date": "Fri, 18 Sep 2020 09:55:30 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: pgbench calculates summary numbers a wrong way." }, { "msg_contents": "At Thu, 17 Sep 2020 17:59:45 +0900 (JST), Kyotaro Horiguchi <horikyota.ntt@gmail.com> wrote in \n> Sigh.. I fixed some more wordings.\n\nThe condition \"all clients took the same time to establish a\nconnection\" is not needed for the transformation, and an intermediate\nexpression was wrong. Fixed them.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center", "msg_date": "Fri, 18 Sep 2020 17:23:36 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": true, "msg_subject": "Re: pgbench calculates summary numbers a wrong way." }, { "msg_contents": "At Fri, 18 Sep 2020 09:55:30 +0200 (CEST), Fabien COELHO <coelho@cri.ensmp.fr> wrote in \n> \n> Hello,\n> \n> >> Sorry, I sent a wrong version of the patch, contains some spelling\n> >> errors. This is the right one.\n> >\n> > Sigh.. I fixed some more wordings.\n> \n> I have submitted a patch which reworks how things are computed so that\n> performance figures make some/more sense, among other things.\n> \n> Maybe you could have a look at it and tell whether it is an\n> improvement wrt your issue?\n\nThanks for the pointer, I'm going to look it.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 18 Sep 2020 17:28:22 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": true, "msg_subject": "Re: pgbench calculates summary numbers a wrong way." }, { "msg_contents": "At Fri, 18 Sep 2020 17:28:22 +0900 (JST), Kyotaro Horiguchi <horikyota.ntt@gmail.com> wrote in \n> > I have submitted a patch which reworks how things are computed so that\n> > performance figures make some/more sense, among other things.\n> > \n> > Maybe you could have a look at it and tell whether it is an\n> > improvement wrt your issue?\n> \n> Thanks for the pointer, I'm going to look it.\n\nI remember about the topic. It started from an issue of thread/client\nconnection synchronization. Current it seems to be added overhauling\nof time counting code. (I think they are in separate patches).\nHowever, the patch doesn't fix my issues.\n\nIf I re-explain my issues in few words:\n\nThe first issue is: in printResuts, conn_total_delay is assumed to be\nthe sum of connection delay of all clients. But actually it is the sum\nof connection delay of all *threads*. As the results the connection\ndelay is underestimated when nclients is larger than nthreads, then\ntps(excluding conn establishment) is too-small on that condition.\n\n\nThe second issue is: estimated latency average (without -L) is\ncalculated as time_include * nclients / <# of completed\ntxns>. Considering that the latency is the time after connection\nestablishement until transaction end, the \"time_include\" should be\ntime_exclude. As the result the estimated (non -L case) average\nlatency gets overestimated than the measured latency (with -L case) if\nconnections takes a long time.\n\nThe patch doesn't affect the first issue, but alleviates the error in\nthe second issue. But still it doesn't handles connection delay\ncorrectly in calculating the value when non -C mode, and doesn't fix\nthe error when -C (conn per tx) mode at all.\n\nSo the two patches are almost orthogonal (but heavily conflicts each\nother^^;). Anyway, it's a good opportunity, so I'll take a look on\nyour patch.\n\nThanks.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 18 Sep 2020 18:39:53 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": true, "msg_subject": "Re: pgbench calculates summary numbers a wrong way." } ]
[ { "msg_contents": "Hello,\n\nIn commits 9f095299 and f98b8476 we improved recovery performance on\nLinux and FreeBSD but we didn't help other operating systems. David\njust confirmed for me that commenting out the PostmasterIsAlive() call\nin the main recovery loop speeds up crash recovery considerably on his\nWindows system: 93s -> 70s or 1.32x faster. So I think we should do\nsomething like what Heikki originally proposed to lower the frequency\nof checks, on systems where we don't have the ability to skip the\ncheck completely. Please see attached.", "msg_date": "Thu, 17 Sep 2020 21:48:17 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "On 17/09/2020 12:48, Thomas Munro wrote:\n> Hello,\n> \n> In commits 9f095299 and f98b8476 we improved recovery performance on\n> Linux and FreeBSD but we didn't help other operating systems. David\n> just confirmed for me that commenting out the PostmasterIsAlive() call\n> in the main recovery loop speeds up crash recovery considerably on his\n> Windows system: 93s -> 70s or 1.32x faster.\n\nNice speedup!\n\n> So I think we should do\n> something like what Heikki originally proposed to lower the frequency\n> of checks, on systems where we don't have the ability to skip the\n> check completely. Please see attached.\n\nIf you put the counter in HandleStartupProcInterrupts(), it could be a \nlong wait if the startup process is e.g. waiting for WAL to arrive in \nthe loop in WaitForWALToBecomeAvailable(), or in recoveryPausesHere(). \nMy original patch only reduced the frequency in the WAL redo loop, when \nyou're actively replaying records.\n\nWe could probably do better on Windows. Maybe the signal handler thread \ncould wait on the PostmasterHandle at the same time that it waits on the \nsignal pipe, and set postmaster_possibly_dead. But I'm not going to work \non that, and it would only help on Windows, so I'm OK with just adding \nthe counter.\n\n- Heikki\n\n\n", "msg_date": "Thu, 17 Sep 2020 13:19:18 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "On Thu, Sep 17, 2020 at 10:19 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> On 17/09/2020 12:48, Thomas Munro wrote:\n> > So I think we should do\n> > something like what Heikki originally proposed to lower the frequency\n> > of checks, on systems where we don't have the ability to skip the\n> > check completely. Please see attached.\n>\n> If you put the counter in HandleStartupProcInterrupts(), it could be a\n> long wait if the startup process is e.g. waiting for WAL to arrive in\n> the loop in WaitForWALToBecomeAvailable(), or in recoveryPausesHere().\n> My original patch only reduced the frequency in the WAL redo loop, when\n> you're actively replaying records.\n\nOh, I checked that WaitForWALToBecomeAvailable() already handled\npostmaster death via events rather than polling, with\nWL_EXIT_ON_PM_DEATH, but I hadn't clocked that recoveryPausesHere()\nuses pg_usleep() and polling. Hmm. Perhaps we should change that\ninstead? The reason I did it that way is that I didn't want to make\nthe new ProcSignalBarrierPending handler less reactive.\n\n> We could probably do better on Windows. Maybe the signal handler thread\n> could wait on the PostmasterHandle at the same time that it waits on the\n> signal pipe, and set postmaster_possibly_dead. But I'm not going to work\n> on that, and it would only help on Windows, so I'm OK with just adding\n> the counter.\n\nYeah, I had the same thought.\n\n\n", "msg_date": "Thu, 17 Sep 2020 22:31:04 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "On 17/09/2020 13:31, Thomas Munro wrote:\n> On Thu, Sep 17, 2020 at 10:19 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>> If you put the counter in HandleStartupProcInterrupts(), it could be a\n>> long wait if the startup process is e.g. waiting for WAL to arrive in\n>> the loop in WaitForWALToBecomeAvailable(), or in recoveryPausesHere().\n>> My original patch only reduced the frequency in the WAL redo loop, when\n>> you're actively replaying records.\n> \n> Oh, I checked that WaitForWALToBecomeAvailable() already handled\n> postmaster death via events rather than polling, with\n> WL_EXIT_ON_PM_DEATH, but I hadn't clocked that recoveryPausesHere()\n> uses pg_usleep() and polling. Hmm. Perhaps we should change that\n> instead? The reason I did it that way is that I didn't want to make\n> the new ProcSignalBarrierPending handler less reactive.\n\nHmm, so for speedy response to postmaster death, you're relying on the \nloops to have other postmaster-death checks besides \nHandleStartupProcInterrupts(), in the form of WL_EXIT_ON_PM_DEATH. That \nseems a bit fragile, at the very least it needs a comment in \nHandleStartupProcInterrupts() to call it out.\n\nNote that there's one more loop in ShutdownWalRcv() that uses pg_usleep().\n\n- Heikki\n\n\n", "msg_date": "Thu, 17 Sep 2020 13:47:31 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "On Thu, Sep 17, 2020 at 10:47 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> Hmm, so for speedy response to postmaster death, you're relying on the\n> loops to have other postmaster-death checks besides\n> HandleStartupProcInterrupts(), in the form of WL_EXIT_ON_PM_DEATH. That\n> seems a bit fragile, at the very least it needs a comment in\n> HandleStartupProcInterrupts() to call it out.\n\nSurely that's the direction we want to go in, though, no? Commit\ncfdf4dc4 was intended to standardise the way we react to postmaster\ndeath where waiting is involved. I updated the comment in\nHandleStartupProcInterrupts() to highlight that the\nPostmasterIsAlive() check in there is only for the benefit of\nCPU-bound loops.\n\n> Note that there's one more loop in ShutdownWalRcv() that uses pg_usleep().\n\nUpdating that one required me to invent a new wait_event for\npg_stat_activity, which seems like progress.\n\nUnfortunately, while I was doing that I realised that WaitLatch()\nwithout WL_SET_LATCH was broken by commit 3347c982bab (in master\nonly), in a way not previously reached by the tests. So 0001 is a\npatch to fix that.", "msg_date": "Fri, 18 Sep 2020 12:30:01 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "\n\nOn 2020/09/18 9:30, Thomas Munro wrote:\n> On Thu, Sep 17, 2020 at 10:47 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>> Hmm, so for speedy response to postmaster death, you're relying on the\n>> loops to have other postmaster-death checks besides\n>> HandleStartupProcInterrupts(), in the form of WL_EXIT_ON_PM_DEATH. That\n>> seems a bit fragile, at the very least it needs a comment in\n>> HandleStartupProcInterrupts() to call it out.\n> \n> Surely that's the direction we want to go in, though, no? Commit\n> cfdf4dc4 was intended to standardise the way we react to postmaster\n> death where waiting is involved. I updated the comment in\n> HandleStartupProcInterrupts() to highlight that the\n> PostmasterIsAlive() check in there is only for the benefit of\n> CPU-bound loops.\n> \n>> Note that there's one more loop in ShutdownWalRcv() that uses pg_usleep().\n> \n> Updating that one required me to invent a new wait_event for\n> pg_stat_activity, which seems like progress.\n> \n> Unfortunately, while I was doing that I realised that WaitLatch()\n> without WL_SET_LATCH was broken by commit 3347c982bab (in master\n> only), in a way not previously reached by the tests. So 0001 is a\n> patch to fix that.\n\n-\t\tpgstat_report_wait_start(WAIT_EVENT_RECOVERY_PAUSE);\n-\t\tpg_usleep(1000000L);\t/* 1000 ms */\n-\t\tpgstat_report_wait_end();\n+\t\tWaitLatch(NULL, WL_EXIT_ON_PM_DEATH | WL_TIMEOUT, 1000,\n+\t\t\t\t WAIT_EVENT_RECOVERY_PAUSE);\n\nThis change may cause at most one second delay against the standby\npromotion request during WAL replay pause? It's only one second,\nbut I'd like to avoid this (unnecessary) wait to shorten the failover time\nas much as possible basically. So what about using WL_SET_LATCH here?\n\nBut when using WL_SET_LATCH, one concern is that walreceiver can\nwake up the startup process too frequently even during WAL replay pause.\nThis is also problematic? I'm ok with this, but if not, using pg_usleep()\nmight be better as the original code does.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Sat, 19 Sep 2020 03:07:09 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "On Sat, Sep 19, 2020 at 6:07 AM Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\n> - pgstat_report_wait_start(WAIT_EVENT_RECOVERY_PAUSE);\n> - pg_usleep(1000000L); /* 1000 ms */\n> - pgstat_report_wait_end();\n> + WaitLatch(NULL, WL_EXIT_ON_PM_DEATH | WL_TIMEOUT, 1000,\n> + WAIT_EVENT_RECOVERY_PAUSE);\n>\n> This change may cause at most one second delay against the standby\n> promotion request during WAL replay pause? It's only one second,\n> but I'd like to avoid this (unnecessary) wait to shorten the failover time\n> as much as possible basically. So what about using WL_SET_LATCH here?\n\nRight, there is a comment saying that we could do that:\n\n * XXX Could also be done with shared latch, avoiding the pg_usleep loop.\n * Probably not worth the trouble though. This state shouldn't be one that\n * anyone cares about server power consumption in.\n\n> But when using WL_SET_LATCH, one concern is that walreceiver can\n> wake up the startup process too frequently even during WAL replay pause.\n> This is also problematic? I'm ok with this, but if not, using pg_usleep()\n> might be better as the original code does.\n\nYou're right, at least if we used recoveryWakeupLatch. Although we'd\nreact to pg_wal_replay_resume() faster, which would be nice, we\nwouldn't be saving energy, we'd be using more energy due to all the\nother latch wakeups that we'd be ignoring. I believe the correct\nsolution to this problem is to add a ConditionVariable\n\"recoveryPauseChanged\" into XLogCtlData, and then broadcast on it in\nSetRecoveryPause(). This would be a trivial change, except for one\nsmall problem: ConditionVariableTimedSleep() contains\nCHECK_FOR_INTERRUPTS(), but startup.c has its own special interrupt\nhandling rather than using ProcessInterrupts() from postgres.c. Maybe\nthat's OK, I'm not sure, but it requires more thought, and I propose\nto keep the existing sloppy polling for now and leave precise wakeup\nimprovements for a separate patch. The primary goal of this patch is\nto switch to the standard treatment of postmaster death in wait loops,\nso that we're free to reduce the sampling frequency in\nHandleStartupProcInterrupts(), to fix a horrible performance problem.\nI have at least tweaked that comment about pg_usleep(), though,\nbecause that was out of date; I also used (void) WaitLatch(...) to\nmake it look like other places where we ignore the return value\n(perhaps some static analyser out there somewhere cares?)\n\nBy the way, a CV could probably be used for walreceiver state changes\ntoo, to improve ShutdownWalRcv().\n\nAlthough I know from CI that this builds and passes \"make check\" on\nWindows, I'm hoping to attract some review of the 0001 patch from a\nWindows person, and confirmation that it passes \"check-world\" (or at\nleast src/test/recovery check) there, because I don't have CI scripts\nfor that yet.", "msg_date": "Sun, 20 Sep 2020 09:29:07 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "On Sun, 20 Sep 2020 at 09:29, Thomas Munro <thomas.munro@gmail.com> wrote:\n>\n> Although I know from CI that this builds and passes \"make check\" on\n> Windows, I'm hoping to attract some review of the 0001 patch from a\n> Windows person, and confirmation that it passes \"check-world\" (or at\n> least src/test/recovery check) there, because I don't have CI scripts\n> for that yet.\n\nI've gone as far as running the recovery tests on the v3-0001 patch\nusing a Windows machine. They pass:\n\nL:\\Projects\\Postgres\\d\\src\\tools\\msvc>vcregress taptest src/test/recovery\n...\nt/001_stream_rep.pl .................. ok\nt/002_archiving.pl ................... ok\nt/003_recovery_targets.pl ............ ok\nt/004_timeline_switch.pl ............. ok\nt/005_replay_delay.pl ................ ok\nt/006_logical_decoding.pl ............ ok\nt/007_sync_rep.pl .................... ok\nt/008_fsm_truncation.pl .............. ok\nt/009_twophase.pl .................... ok\nt/010_logical_decoding_timelines.pl .. ok\nt/011_crash_recovery.pl .............. skipped: Test fails on Windows perl\nt/012_subtransactions.pl ............. ok\nt/013_crash_restart.pl ............... ok\nt/014_unlogged_reinit.pl ............. ok\nt/015_promotion_pages.pl ............. ok\nt/016_min_consistency.pl ............. ok\nt/017_shm.pl ......................... skipped: SysV shared memory not\nsupported by this platform\nt/018_wal_optimize.pl ................ ok\nt/019_replslot_limit.pl .............. ok\nt/020_archive_status.pl .............. ok\nAll tests successful.\nFiles=20, Tests=222, 397 wallclock secs ( 0.08 usr + 0.00 sys = 0.08 CPU)\nResult: PASS\n\nL:\\Projects\\Postgres\\d\\src\\tools\\msvc>git diff --stat\n src/backend/storage/ipc/latch.c | 23 +++++++++++++++++++----\n 1 file changed, 19 insertions(+), 4 deletions(-)\n\nDavid\n\n\n", "msg_date": "Wed, 23 Sep 2020 14:27:05 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "On Wed, Sep 23, 2020 at 2:27 PM David Rowley <dgrowleyml@gmail.com> wrote:\n> I've gone as far as running the recovery tests on the v3-0001 patch\n> using a Windows machine. They pass:\n\nThanks! I pushed that one, because it was effectively a bug fix\n(WaitLatch() without a latch was supposed to work).\n\nI'll wait longer for feedback on the main patch; perhaps someone has a\nbetter idea, or wants to take issue with the magic number 1024 (ie\nlimit on how many records we'll replay before we notice the postmaster\nhas exited), or my plan to harmonise those wait loops? It has a CF\nentry for the next CF.\n\n\n", "msg_date": "Wed, 23 Sep 2020 15:47:19 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "\n\nOn 2020/09/23 12:47, Thomas Munro wrote:\n> On Wed, Sep 23, 2020 at 2:27 PM David Rowley <dgrowleyml@gmail.com> wrote:\n>> I've gone as far as running the recovery tests on the v3-0001 patch\n>> using a Windows machine. They pass:\n> \n> Thanks! I pushed that one, because it was effectively a bug fix\n> (WaitLatch() without a latch was supposed to work).\n\nGreat!\n\n\n> \n> I'll wait longer for feedback on the main patch; perhaps someone has a\n> better idea, or wants to take issue with the magic number 1024 (ie\n> limit on how many records we'll replay before we notice the postmaster\n> has exited), or my plan to harmonise those wait loops? It has a CF\n> entry for the next CF.\n\nDoes this patch work fine with warm-standby case using pg_standby?\nIIUC the startup process doesn't call WaitLatch() in that case, so ISTM that,\nwith the patch, it cannot detect the postmaster death immediately.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Wed, 23 Sep 2020 23:39:10 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "On Thu, Sep 24, 2020 at 2:39 AM Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\n> Does this patch work fine with warm-standby case using pg_standby?\n> IIUC the startup process doesn't call WaitLatch() in that case, so ISTM that,\n> with the patch, it cannot detect the postmaster death immediately.\n\nRight, RestoreArchivedFile() uses system(), so I guess it can hang\naround for a long time after unexpected postmaster exit on every OS if\nthe command waits. To respond to various kinds of important\ninterrupts, I suppose that'd ideally use something like\nOpenPipeStream() and a typical WaitLatch() loop with CFI(). I'm not\nsure what our policy is or should be for exiting while we have running\nsubprocesses. I guess that is a separate issue.\n\nHere's a rebase, no code change.", "msg_date": "Thu, 24 Sep 2020 17:55:17 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "On Thu, Sep 24, 2020 at 05:55:17PM +1200, Thomas Munro wrote:\n> Right, RestoreArchivedFile() uses system(), so I guess it can hang\n> around for a long time after unexpected postmaster exit on every OS if\n> the command waits. To respond to various kinds of important\n> interrupts, I suppose that'd ideally use something like\n> OpenPipeStream() and a typical WaitLatch() loop with CFI(). I'm not\n> sure what our policy is or should be for exiting while we have running\n> subprocesses. I guess that is a separate issue.\n\n- if (IsUnderPostmaster && !PostmasterIsAlive())\n+ if (IsUnderPostmaster &&\n+#ifndef USE_POSTMASTER_DEATH_SIGNAL\n+ count++ % 1024 == 0 &&\n+#endif\n+ !PostmasterIsAlive())\nThat's pretty hack-ish, still efficient. Could we consider a\ndifferent approach like something relying on\nPostmasterIsAliveInternal() with repetitive call handling? This may\nnot be the only place where we care about that, particularly for\nnon-core code. \n\nNo objections with the two changes from pg_usleep() to WaitLatch() so\nthey could be applied separately first.\n--\nMichael", "msg_date": "Mon, 16 Nov 2020 16:56:06 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: PostmasterIsAlive() in recovery\n (non-USE_POST_MASTER_DEATH_SIGNAL builds)" }, { "msg_contents": "On Mon, Nov 16, 2020 at 8:56 PM Michael Paquier <michael@paquier.xyz> wrote:\n> On Thu, Sep 24, 2020 at 05:55:17PM +1200, Thomas Munro wrote:\n> > Right, RestoreArchivedFile() uses system(), so I guess it can hang\n> > around for a long time after unexpected postmaster exit on every OS if\n> > the command waits. To respond to various kinds of important\n> > interrupts, I suppose that'd ideally use something like\n> > OpenPipeStream() and a typical WaitLatch() loop with CFI(). I'm not\n> > sure what our policy is or should be for exiting while we have running\n> > subprocesses. I guess that is a separate issue.\n>\n> - if (IsUnderPostmaster && !PostmasterIsAlive())\n> + if (IsUnderPostmaster &&\n> +#ifndef USE_POSTMASTER_DEATH_SIGNAL\n> + count++ % 1024 == 0 &&\n> +#endif\n> + !PostmasterIsAlive())\n> That's pretty hack-ish, still efficient. Could we consider a\n> different approach like something relying on\n> PostmasterIsAliveInternal() with repetitive call handling? This may\n> not be the only place where we care about that, particularly for\n> non-core code.\n\nAs far as I know there aren't any other places that do polling of\nPostmasterIsAlive() in a loop like this. All others have been removed\nfrom core code: either they already had a WaitLatch() or similar so it\nwe just had to add WL_EXIT_ON_PM_DEATH, or they do pure CPU-bound and\ndon't actively try to detect postmaster death. That's why it seems\nutterly insane that here we try to detect it X million times per\nsecond.\n\n> No objections with the two changes from pg_usleep() to WaitLatch() so\n> they could be applied separately first.\n\nI thought about committing that first part, and got as far as\nsplitting the patch into two (see attached), but then I re-read\nFujii-san's message about the speed of promotion and realised that we\nreally should have something like a condition variable for walRcvState\nchanges. I'll look into that.", "msg_date": "Tue, 2 Mar 2021 00:00:08 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "On Tue, Mar 2, 2021 at 12:00 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n> On Mon, Nov 16, 2020 at 8:56 PM Michael Paquier <michael@paquier.xyz> wrote:\n> > No objections with the two changes from pg_usleep() to WaitLatch() so\n> > they could be applied separately first.\n>\n> I thought about committing that first part, and got as far as\n> splitting the patch into two (see attached), but then I re-read\n> Fujii-san's message about the speed of promotion and realised that we\n> really should have something like a condition variable for walRcvState\n> changes. I'll look into that.\n\nHere's an experimental attempt at that, though I'm not sure if it's\nthe right approach. Of course it's not necessary to use condition\nvariables here: we could use recoveryWakeupLatch, because we're not in\nany doubt about who needs to be woken up. But then you could get\nconstant wakeups while recovery is paused, unless you also suppressed\nthat somehow. You could use the startup process's procLatch,\nadvertised in shmem, but that's almost a condition variable. With a\ncondition variable, you get to name it something like\nwalRcvStateChanged, and then the programming rule is very clear: if\nyou change walRcvState, you need to broadcast that fact (and you don't\nhave to worry about who might be interested). One question I haven't\ngot to the bottom of: is it a problem for the startup process that CVs\nuse CHECK_FOR_INTERRUPTS()?", "msg_date": "Tue, 2 Mar 2021 14:10:20 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "On Tue, Mar 2, 2021 at 2:10 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> ... One question I haven't\n> got to the bottom of: is it a problem for the startup process that CVs\n> use CHECK_FOR_INTERRUPTS()?\n\nThis was a red herring. The startup process already reaches CFI() via\nvarious paths, as I figured out pretty quickly with a debugger. So\nI'd like to go ahead and commit these patches.\n\nMichael, when you said \"That's pretty hack-ish, still efficient\" in\nreference to this code:\n\n> - if (IsUnderPostmaster && !PostmasterIsAlive())\n> + if (IsUnderPostmaster &&\n> +#ifndef USE_POSTMASTER_DEATH_SIGNAL\n> + count++ % 1024 == 0 &&\n> +#endif\n> + !PostmasterIsAlive())\n\nIs that an objection, and do you see a specific better way?\n\nI know that someone just needs to write a Windows patch to get us a\npostmaster death signal when the postmaster's event fires, and then\nthe problem will go away on Windows. I still want this change,\nbecause we don't have such a patch yet, and even when someone writes\nthat, there are still a couple of Unixes that could benefit.\n\n\n", "msg_date": "Thu, 11 Mar 2021 16:37:39 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "On Thu, Mar 11, 2021 at 04:37:39PM +1300, Thomas Munro wrote:\n> Michael, when you said \"That's pretty hack-ish, still efficient\" in\n> reference to this code:\n> \n>> - if (IsUnderPostmaster && !PostmasterIsAlive())\n>> + if (IsUnderPostmaster &&\n>> +#ifndef USE_POSTMASTER_DEATH_SIGNAL\n>> + count++ % 1024 == 0 &&\n>> +#endif\n>> + !PostmasterIsAlive())\n> \n> Is that an objection, and do you see a specific better way?\n\nI'd like to believe that there are more elegant ways to write that,\nbut based on the numbers you are giving, there is too much gain here\nto ignore it. I would avoid 1024 as a hardcoded value though, so you\ncould just stick that in a #define or such. So please feel free to go\nahead. Thanks for asking.\n\n> I know that someone just needs to write a Windows patch to get us a\n> postmaster death signal when the postmaster's event fires, and then\n> the problem will go away on Windows. I still want this change,\n> because we don't have such a patch yet, and even when someone writes\n> that, there are still a couple of Unixes that could benefit.\n\nWow. This probably means that we would be able to get rid of\nUSE_POSTMASTER_DEATH_SIGNAL?\n--\nMichael", "msg_date": "Thu, 11 Mar 2021 15:34:24 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: PostmasterIsAlive() in recovery\n (non-USE_POST_MASTER_DEATH_SIGNAL builds)" }, { "msg_contents": "On Thu, Mar 11, 2021 at 7:34 PM Michael Paquier <michael@paquier.xyz> wrote:\n> On Thu, Mar 11, 2021 at 04:37:39PM +1300, Thomas Munro wrote:\n> > Michael, when you said \"That's pretty hack-ish, still efficient\" in\n> > reference to this code:\n> >\n> >> - if (IsUnderPostmaster && !PostmasterIsAlive())\n> >> + if (IsUnderPostmaster &&\n> >> +#ifndef USE_POSTMASTER_DEATH_SIGNAL\n> >> + count++ % 1024 == 0 &&\n> >> +#endif\n> >> + !PostmasterIsAlive())\n> >\n> > Is that an objection, and do you see a specific better way?\n>\n> I'd like to believe that there are more elegant ways to write that,\n> but based on the numbers you are giving, there is too much gain here\n> to ignore it. I would avoid 1024 as a hardcoded value though, so you\n> could just stick that in a #define or such. So please feel free to go\n> ahead. Thanks for asking.\n\nThanks! I rebased over the recent recovery pause/resume state\nmanagement change and simplified the walRcvState patch a bit (no need\nto broadcast for every state change, just the changes to STOPPED\nstate). So that gets us to the point where there are no loops with\nHandleStartupProcInterrupts() and a sleep in them (that'd be bad, it'd\ntake a long time to notice the postmaster going away if it only checks\nevery 1024 loops; all loops that sleep need to be using the latch\ninfrastructure so they can notice the postmaster exiting immediately).\nThen I turned that 1024 into a macro as you suggested for the main\npatch, and pushed.\n\nIt looks like RecoveryRequiresIntParameter() should be sharing code\nwith recoveryPausesHere(), but I didn't try to do that in this commit.\n\n> > I know that someone just needs to write a Windows patch to get us a\n> > postmaster death signal when the postmaster's event fires, and then\n> > the problem will go away on Windows. I still want this change,\n> > because we don't have such a patch yet, and even when someone writes\n> > that, there are still a couple of Unixes that could benefit.\n>\n> Wow. This probably means that we would be able to get rid of\n> USE_POSTMASTER_DEATH_SIGNAL?\n\nWe'll still need it, because there'd still be systems with no signal:\nNetBSD, OpenBSD, AIX, HPUX, illumos.\n\n\n", "msg_date": "Fri, 12 Mar 2021 19:55:59 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "On 2021/03/02 10:10, Thomas Munro wrote:\n> On Tue, Mar 2, 2021 at 12:00 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n>> On Mon, Nov 16, 2020 at 8:56 PM Michael Paquier <michael@paquier.xyz> wrote:\n>>> No objections with the two changes from pg_usleep() to WaitLatch() so\n>>> they could be applied separately first.\n>>\n>> I thought about committing that first part, and got as far as\n>> splitting the patch into two (see attached), but then I re-read\n>> Fujii-san's message about the speed of promotion and realised that we\n>> really should have something like a condition variable for walRcvState\n>> changes. I'll look into that.\n> \n> Here's an experimental attempt at that, though I'm not sure if it's\n> the right approach. Of course it's not necessary to use condition\n> variables here: we could use recoveryWakeupLatch, because we're not in\n> any doubt about who needs to be woken up. But then you could get\n> constant wakeups while recovery is paused, unless you also suppressed\n> that somehow. You could use the startup process's procLatch,\n> advertised in shmem, but that's almost a condition variable. With a\n> condition variable, you get to name it something like\n> walRcvStateChanged, and then the programming rule is very clear: if\n> you change walRcvState, you need to broadcast that fact (and you don't\n> have to worry about who might be interested). One question I haven't\n> got to the bottom of: is it a problem for the startup process that CVs\n> use CHECK_FOR_INTERRUPTS()?\n\nI found 0001 patch was committed in de829ddf23, and which added new\nwait event WalrcvExit. This name seems not consistent with other wait\nevents. I'm thinking it's better to rename it to WalReceiverExit. Thought?\nPatch attached.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION", "msg_date": "Tue, 23 Mar 2021 10:43:59 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "On Tue, Mar 23, 2021 at 2:44 PM Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\n> I found 0001 patch was committed in de829ddf23, and which added new\n> wait event WalrcvExit. This name seems not consistent with other wait\n> events. I'm thinking it's better to rename it to WalReceiverExit. Thought?\n> Patch attached.\n\nAgreed, your names are better. Thanks.\n\n\n", "msg_date": "Tue, 23 Mar 2021 14:52:25 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "\n\nOn 2021/03/23 10:52, Thomas Munro wrote:\n> On Tue, Mar 23, 2021 at 2:44 PM Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\n>> I found 0001 patch was committed in de829ddf23, and which added new\n>> wait event WalrcvExit. This name seems not consistent with other wait\n>> events. I'm thinking it's better to rename it to WalReceiverExit. Thought?\n>> Patch attached.\n> \n> Agreed, your names are better. Thanks.\n\nThanks! I will commit the patch.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Tue, 23 Mar 2021 14:49:08 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "\n\nOn 2021/03/23 14:49, Fujii Masao wrote:\n> \n> \n> On 2021/03/23 10:52, Thomas Munro wrote:\n>> On Tue, Mar 23, 2021 at 2:44 PM Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\n>>> I found 0001 patch was committed in de829ddf23, and which added new\n>>> wait event WalrcvExit. This name seems not consistent with other wait\n>>> events. I'm thinking it's better to rename it to WalReceiverExit. Thought?\n>>> Patch attached.\n>>\n>> Agreed, your names are better.  Thanks.\n> \n> Thanks! I will commit the patch.\n\nPushed. Thanks!\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Wed, 24 Mar 2021 10:41:20 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "On Fri, Mar 12, 2021 at 7:55 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> On Thu, Mar 11, 2021 at 7:34 PM Michael Paquier <michael@paquier.xyz> wrote:\n> > Wow. This probably means that we would be able to get rid of\n> > USE_POSTMASTER_DEATH_SIGNAL?\n>\n> We'll still need it, because there'd still be systems with no signal:\n> NetBSD, OpenBSD, AIX, HPUX, illumos.\n\nErm, and of course macOS.\n\nThere is actually something we could do here: ioctl(I_SETSIG) for\nSysV-derived systems and fcntl(O_ASYNC) for BSD-derived systems seems\nlike a promising way to get a SIGIO signal when the postmaster goes\naway and the pipe becomes readable. Previously I'd discounted this,\nbecause it's not in POSIX and I doubted it would work well on other\nsystems. But I was flicking through Stevens' UNIX book while trying\nto figure out that POLLHUP stuff from a nearby thread (though it's\nuseless for that purpose) and I learned from section 12.6 that SIGIO\nis fairly ancient, originating in 4.2BSD, adopted by SVR4, so it's\nlikely present in quite a few systems, maybe even all of our support\nplatforms if we're prepared to do it two different ways. Just a\nthought.\n\n\n", "msg_date": "Wed, 31 Mar 2021 19:02:12 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "On Wed, Mar 31, 2021 at 7:02 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> On Fri, Mar 12, 2021 at 7:55 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> > On Thu, Mar 11, 2021 at 7:34 PM Michael Paquier <michael@paquier.xyz> wrote:\n> > > Wow. This probably means that we would be able to get rid of\n> > > USE_POSTMASTER_DEATH_SIGNAL?\n> >\n> > We'll still need it, because there'd still be systems with no signal:\n> > NetBSD, OpenBSD, AIX, HPUX, illumos.\n>\n> Erm, and of course macOS.\n>\n> There is actually something we could do here: ioctl(I_SETSIG) for\n> SysV-derived systems and fcntl(O_ASYNC) for BSD-derived systems seems\n> like a promising way to get a SIGIO signal when the postmaster goes\n> away and the pipe becomes readable. Previously I'd discounted this,\n> because it's not in POSIX and I doubted it would work well on other\n> systems. But I was flicking through Stevens' UNIX book while trying\n> to figure out that POLLHUP stuff from a nearby thread (though it's\n> useless for that purpose) and I learned from section 12.6 that SIGIO\n> is fairly ancient, originating in 4.2BSD, adopted by SVR4, so it's\n> likely present in quite a few systems, maybe even all of our support\n> platforms if we're prepared to do it two different ways. Just a\n> thought.\n\nAlright, here's a proof-of-concept patch that does that. Adding to the next CF.\n\nThis seems to work on Linux, macOS, FreeBSD and OpenBSD (and I assume\nany other BSD). Can anyone tell me if it works on illumos, AIX or\nHPUX, and if not, how to fix it or disable the feature gracefully?\nFor now the patch assumes that if you have SIGIO then you can do this;\nperhaps it should also test for O_ASYNC? Perhaps HPUX has the signal\nbut requires a different incantation with I_SETSIG?\n\nFull disclosure: The reason for my interest in this subject is that I\nhave a work-in-progress patch set to make latches, locks and condition\nvariables more efficient using futexes on several OSes, but it needs a\nsignal to wake on postmaster death.", "msg_date": "Fri, 9 Apr 2021 16:01:28 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "On 09/04/2021 07:01, Thomas Munro wrote:\n> On Wed, Mar 31, 2021 at 7:02 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n>> On Fri, Mar 12, 2021 at 7:55 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n>>> On Thu, Mar 11, 2021 at 7:34 PM Michael Paquier <michael@paquier.xyz> wrote:\n>>>> Wow. This probably means that we would be able to get rid of\n>>>> USE_POSTMASTER_DEATH_SIGNAL?\n>>>\n>>> We'll still need it, because there'd still be systems with no signal:\n>>> NetBSD, OpenBSD, AIX, HPUX, illumos.\n>>\n>> Erm, and of course macOS.\n>>\n>> There is actually something we could do here: ioctl(I_SETSIG) for\n>> SysV-derived systems and fcntl(O_ASYNC) for BSD-derived systems seems\n>> like a promising way to get a SIGIO signal when the postmaster goes\n>> away and the pipe becomes readable. Previously I'd discounted this,\n>> because it's not in POSIX and I doubted it would work well on other\n>> systems. But I was flicking through Stevens' UNIX book while trying\n>> to figure out that POLLHUP stuff from a nearby thread (though it's\n>> useless for that purpose) and I learned from section 12.6 that SIGIO\n>> is fairly ancient, originating in 4.2BSD, adopted by SVR4, so it's\n>> likely present in quite a few systems, maybe even all of our support\n>> platforms if we're prepared to do it two different ways. Just a\n>> thought.\n> \n> Alright, here's a proof-of-concept patch that does that. Adding to the next CF.\n\nLooks good to me.\n\n> This seems to work on Linux, macOS, FreeBSD and OpenBSD (and I assume\n> any other BSD). Can anyone tell me if it works on illumos, AIX or\n> HPUX, and if not, how to fix it or disable the feature gracefully?\n> For now the patch assumes that if you have SIGIO then you can do this;\n> perhaps it should also test for O_ASYNC? Perhaps HPUX has the signal\n> but requires a different incantation with I_SETSIG?\n\nI think it would be OK to just commit this (after REL_14_STABLE has been \ncreated) and see what breaks in the buildfarm. Then we'll at least know \nif we need more autoconf checks or something to disable this.\n\n- Heikki\n\n\n", "msg_date": "Thu, 10 Jun 2021 14:38:55 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "Heikki Linnakangas <hlinnaka@iki.fi> writes:\n> On 09/04/2021 07:01, Thomas Munro wrote:\n>> This seems to work on Linux, macOS, FreeBSD and OpenBSD (and I assume\n>> any other BSD). Can anyone tell me if it works on illumos, AIX or\n>> HPUX, and if not, how to fix it or disable the feature gracefully?\n>> For now the patch assumes that if you have SIGIO then you can do this;\n>> perhaps it should also test for O_ASYNC? Perhaps HPUX has the signal\n>> but requires a different incantation with I_SETSIG?\n\nI took a look on HPUX 10.20 (gaur's host):\n\n* SIGIO exists, but signal.h only defines it with \n-D_INCLUDE_HPUX_SOURCE which we don't use.\n\n* I found I_SETSIG, but ...\n\n$ grep -r SETSIG /usr/include \n/usr/include/sys/stropts.h:#define I_SETSIG _IO('S', 9) /* request SIGPOLL signal on events */\n\nstropts.h seems to be for a feature called \"streams\", which is\nprobably nonstandard enough that we don't want to deal with it.\n\nSo I think the short answer on this platform is that if you conditionalize\non #ifdef SIGIO then it will just not do it, and we should be fine.\n\nCan't say about HPUX 11.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 10 Jun 2021 21:18:38 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" }, { "msg_contents": "On Fri, Jun 11, 2021 at 1:18 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Heikki Linnakangas <hlinnaka@iki.fi> writes:\n> > On 09/04/2021 07:01, Thomas Munro wrote:\n> >> This seems to work on Linux, macOS, FreeBSD and OpenBSD (and I assume\n> >> any other BSD). Can anyone tell me if it works on illumos, AIX or\n> >> HPUX, and if not, how to fix it or disable the feature gracefully?\n> >> For now the patch assumes that if you have SIGIO then you can do this;\n> >> perhaps it should also test for O_ASYNC? Perhaps HPUX has the signal\n> >> but requires a different incantation with I_SETSIG?\n>\n> I took a look on HPUX 10.20 (gaur's host):\n\nThanks both for looking!\n\nUnfortunately I'll have to withdraw this patch in its current form.\nOn closer inspection, only the last backend to start up and do\nF_SETOWN on the pipe receives the signal. We'd probably have to\ncreate a separate pipe for each backend, or something like that, which\nseems unwarranted so far.\n\n> * I found I_SETSIG, but ...\n>\n> $ grep -r SETSIG /usr/include\n> /usr/include/sys/stropts.h:#define I_SETSIG _IO('S', 9) /* request SIGPOLL signal on events */\n>\n> stropts.h seems to be for a feature called \"streams\", which is\n> probably nonstandard enough that we don't want to deal with it.\n\nAgreed. It is technically POSIX, but optional and marked obsolescent.\nIt's annoying to see that I_SETSIG did allow multiple processes to\nregister to receive signals for the same event on the same underlying\nstream, unlike F_SETOWN. Oh well.\n\n\n", "msg_date": "Tue, 13 Jul 2021 00:18:15 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: PostmasterIsAlive() in recovery (non-USE_POST_MASTER_DEATH_SIGNAL\n builds)" } ]